モデルのコレクション内の個々のアイテムの変更を保存する必要がありますか、モデルを保存するときに呼び出す方法があります。Rails/ActiveRecord:モデルの関連するコレクションへの変更を保存
#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のコピーは、DB(コピーの異なる数に注意してください)にコピーを更新していないようです。
私はbefore_saveコールバックのアイデアを好きですが、私は爆発的再帰を心配したい - 私はここにある別のシナリオでは、顧客とDVDそれぞれが多くのレンタルを持っているので、私は、customer.rentals.first.dvd.rentals.first.customerと言うことができますし、カスケードbefore_savesは少し手を出すかもしれない、と心配します。 – rampion