简体   繁体   English

Rails:ActiveRecord和send;如何只知道类名来设置activerecord实例的关系?

[英]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.

相关问题 如何获取为其创建ActiveRecord :: Relation实例的ActiveRecord类? - How can I get the ActiveRecord class for which an ActiveRecord::Relation instance was created? Rails ActiveRecord-如何确定多态关系中的所有者? - Rails ActiveRecord - How do I determine the owner in a polymorphic relation? 如何取回 ActiveRecord 而不是 ActiveRecord 关系? - How do I get back an ActiveRecord instead of an ActiveRecord relation? Rails - 有没有办法为模型的 ActiveRecord::Relation 查询设置可覆盖的“默认”过滤器(即预运行类方法)? - Rails - Is there any way to set an overrideable "default" filter (i.e. pre-run class method) for a model's ActiveRecord::Relation queries? (Rails,ActiveRecord)如何在仍检索字段名称的同时使用ActiveRecord计算? - (Rails, ActiveRecord) How do I use ActiveRecord calculations while still retrieving field names? 如何浏览ActiveRecord关系的结果? - How do I explore the results of an ActiveRecord relation? 如何在Ruby On Rails中设置:through ActiveRecord关联? - How do I set up a :through ActiveRecord association in Ruby On Rails? 如何将数组添加到rails中的activerecord类 - How do i add an array to an activerecord class in rails 如何将ActiveRecord添加到没有ActiveRecord初始化的rails应用程序? - How do I add ActiveRecord to a rails app initialized without ActiveRecord? 如何在Rails中基于ActiveRecord_Relation获得ActiveRecord_Relation? - How to get ActiveRecord_Relation based on a ActiveRecord_Relation in rails?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM