Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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})
like image 391
Zando Avatar asked May 10 '11 17:05

Zando


1 Answers

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.

like image 63
jesse reiss Avatar answered Sep 19 '22 22:09

jesse reiss