为Activerecord模型分配关联而不自动保存

时间:2013-10-04 11:42:20

标签: ruby-on-rails ruby api activerecord filtering

我想在API控制器中过滤嵌套关联,然后重新分配过滤后的关联,只过滤后的关联将从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

有没有办法“停用”隐式保存/更新?

1 个答案:

答案 0 :(得分:2)

如果您的most_loved_children可以作为属性哈希集合收集,那么您可以使用“

parent.children.build( most_loved_children )

不会立即保存。