Rails / ActiveRecord:保存对模型关联集合的更改

我是否必须保存对模型集合中各个项目的修改,或者是否有一种方法可以在保存模型时调用它来保存它们。

#save似乎没有这样做。 例如:

 irb> rental = #... #=> # irb> rental.dvd #=> #<Dvd id: 3252, title: "The Women of Summer", year: 1986, copies: 20, is_new: false, is_discontinued: false, list_price: #, sale_price: #> irb> rental.dvd.copies += 1 #=> 21 irb> rental.save #=> true irb> rental.dvd #=> #<Dvd id: 3252, title: "The Women of Summer", year: 1986, copies: 21, is_new: false, is_discontinued: false, list_price: #, sale_price: #> irb> Dvd.find_by_title('The Women of Summer') #=> #<Dvd id: 3252, title: "The Women of Summer", year: 1986, copies: 20, is_new: false, is_discontinued: false, list_price: #, sale_price: #> 

在上面的示例中,租借的DVD副本似乎没有更新DB中的副本(请注意不同的副本数)。

只需在增加值后执行rental.dvd.save,或者在上面的情况下可以使用

 rental.dvd.increment!(:copies) 

这也会自动保存,注意’!’ 在增量!

通过在声明关联时添加:autosave => true选项,可以将ActiveRecord配置为级联保存对模型集合中项目的更改。 阅读更多 。

例:

 class Payment < ActiveRecord::Base belongs_to :cash_order, :autosave => true ... end 

你必须自己做

这不完全正确。 您可以使用强制保存的“构建”方法。 例如,假设您有公司模型和员工(公司has_many员工)。 你可以这样做:

 acme = Company.new({:name => "Acme, Inc"}) acme.employees.build({:first_name => "John"}) acme.employees.build({:first_name => "Mary"}) acme.employees.build({:first_name => "Sue"}) acme.save 

将创建所有4条记录,公司记录和3条Employee记录,并将company_id适当地下推到Employee对象。

你必须自己做。 初始保存后,Active Record不会在has_many关系中级联保存操作。

您可以使用before_save回调自动执行该过程。

这篇文章很有用: http : //erikonrails.snowedin.net/?p = 267

Erik描述了如何在模型中使用“accepts_nested_attributes_for”和在视图中使用<%f.fields_for%>来完成工作。

详细说明见: http : //api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html