So I'm iterating through all my AR's and setting their relationships dynamically...so I know that I have SomeObject and that it belongs_to ManyObjects...I want to do something like this:
an_object.some_relation = related_object
an_object.save
Is there a way to do this through send or some similar such method? This of course doesn't work:
an_object.send(some_relation_name, related_object)
This works, I'm just interested in doing it a less dangerous, more Rails-meta way:
an_object.update_attributes({"#{some_relation_name}_id"=>related_object.id})
Well you could do
an_object.send("#{some_relation_name}=", related_object)
Which is just dynamically calling the setter method.
Or you could go a little lower level and use :
an_object.reflect_on_association(some_relation_name).build_association(related_object_attributes)
I'd go with the first, it's a little "scary" to use send sometimes, but that's what ruby is all about, dynamic programming.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With