Rails:ActiveRecord 和发送;如何在只知道类名的情况下设置 activerecord 实例的关系?
因此,我正在迭代所有 AR 并动态设置它们的关系...所以我知道我有 SomeObject 并且它属于 ManyObjects...我想做这样的事情:
an_object.some_relation = related_object
an_object.save
有没有办法通过 发送或类似的方法?这当然行不通:
an_object.send(some_relation_name, related_object)
这是行得通的,我只是有兴趣以一种危险性较小、更加 Rails-meta 的方式来做:
an_object.update_attributes({"#{some_relation_name}_id"=>related_object.id})
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})
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
那么你可以做
这只是动态调用 setter 方法。
或者你可以降低一点级别并使用:
我会选择第一个,有时使用 send 有点“可怕”,但这就是 ruby 的全部内容,动态编程。
Well you could do
Which is just dynamically calling the setter method.
Or you could go a little lower level and use :
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.