轨道/ ActiveRecord的:更改保存到模型的关联集合 [英] Rails/ActiveRecord: save changes to a model's associated collections

查看:158
本文介绍了轨道/ ActiveRecord的:更改保存到模型的关联集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一定要保存修改单个项目集合中的一个模型,或者是有一种方法,我可以打电话来拯救他们,当我保存模型。

Do I have to save modifications to individual items in a collection for a model, or is there a method I can call to save them when I save the model.

#save 似乎并没有做到这一点。例如:

#save doesn't seem to do it. For example:

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(注意拷贝的不同数目)。

In the above example, the copy of the DVD that the rental has doesn't seem to update the copy in the DB (note the differing number of copies).

推荐答案

只是做一个rental.dvd.save您递增值之后,或者在上述情况下,你可以使用

just do a rental.dvd.save after you increment the value or in the above case you could use

rental.dvd.increment!(:copies)

这也将自动保存,注意'!增量的!

which will also automatically save, note the '!' on increment!

这篇关于轨道/ ActiveRecord的:更改保存到模型的关联集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆