Zando
Zando

Reputation: 5555

Rails: ActiveRecord and send; how do I set an activerecord instance's relation with only knowing the class names?

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})

Upvotes: 6

Views: 3614

Answers (1)

jesse reiss
jesse reiss

Reputation: 4579

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.

Upvotes: 15

Related Questions