我想过滤 API Controller 中的嵌套关联,然后重新分配过滤后的关联,这样 API 只会返回过滤后的关联。
class Parent < ActiveRecord::Base
has_many :children
end
class Child < ActiveRecord::Base
belongs_to :parent
end
parent = Parent.find(1)
most_loved_children = []
# do some filtering
parent.children = most_loved_children # triggers save on each of the children
parent.to_json # should only return parent with most_loved_children
有没有办法“停用”隐式保存/更新?
最佳答案
如果您的 most_loved_children
可以收集为属性散列集,那么您可以使用“
parent.children.build( most_loved_children )
这不会立即保存。
关于ruby-on-rails - 在没有自动保存的情况下为 Activerecord 模型分配关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19180352/