[英]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: 所以我正在迭代我所有的AR并动态设置它们的关系...所以我知道我有SomeObject并且它属于ManyObjects ...我想做这样的事情:
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: 这是有效的,我只是想做一个不那么危险,更多Rails-meta方式:
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. 这只是动态调用setter方法。
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. 我会选择第一个,有时使用send有点“可怕”,但这就是ruby的全部,动态编程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.