gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 07:10:13 25 4
gpt4 key购买 nike

所以我遍历我所有的 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})

最佳答案

你可以的

an_object.send("#{some_relation_name}=", related_object)

这只是动态调用setter方法。

或者你可以降低一点并使用:

an_object.reflect_on_association(some_relation_name).build_association(related_object_attributes)

我会选择第一个,有时使用 send 有点“可怕”,但这就是 ruby​​ 的全部,动态编程。

关于ruby-on-rails - rails : ActiveRecord and send; how do I set an activerecord instance's relation with only knowing the class names?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5953918/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com