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

ram*_*ion 7 ruby activerecord ruby-on-rails

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

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

irb> rental = #...
#=> #<Rental id: 18737, customer_id: 61, dvd_id: 3252, date_rented: "2008-12-16 05:00:00", date_shipped: "2008-12-16 05:00:00", date_returned: "2008-12-22 05:00:00">
irb> rental.dvd
#=> #<Dvd id: 3252, title: "The Women of Summer", year: 1986, copies: 20, is_new: false, is_discontinued: false, list_price: #<BigDecimal:1a48f0c,'0.1599E2',8(8)>, sale_price: #<BigDecimal:1a48ed0,'0.1599E2',8(8)>>
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: #<BigDecimal:1a2e9cc,'0.1599E2',8(8)>, sale_price: #<BigDecimal:1a2e97c,'0.1599E2',8(8)>>
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: #<BigDecimal:1a30164,'0.1599E2',8(8)>, sale_price: #<BigDecimal:1a30128,'0.1599E2',8(8)>>
Run Code Online (Sandbox Code Playgroud)

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

moc*_*dev 22

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

例:

class Payment < ActiveRecord::Base
    belongs_to :cash_order, :autosave => true
    ...
end
Run Code Online (Sandbox Code Playgroud)


Cor*_*ook 2

只需在增加值后执行 Rental.dvd.save 即可,或者在上述情况下您可以使用

rental.dvd.increment!(:copies)
Run Code Online (Sandbox Code Playgroud)

这也会自动保存,注意“!” 增量!