我是否必须保存对模型集合中单个项目的修改,或者是否有一种方法可以在我保存模型时调用以保存它们。
#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)>>
在上面的例子中,租赁的 DVD 副本似乎没有更新数据库中的副本(注意不同的副本数)。
最佳答案
您可以通过在声明关联时添加 :autosave => true
选项,将 ActiveRecord 配置为级联保存对模型集合中项目的更改。 Read more .
例子:
class Payment < ActiveRecord::Base
belongs_to :cash_order, :autosave => true
...
end
关于ruby-on-rails - rails/事件记录 : save changes to a model's associated collections,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/869873/