保存Rails模型的所有属性

时间:2021-04-30 13:25:52

I have a user model that has many carts

我有一个有很多购物车的用户模型

class User < ActiveRecord::Base
  has_many :carts

If I update a cart:

如果我更新购物车:

User.last.carts.last.time_purchased = Time.now

Is there a way I can save the whole user model? Now, if I call

有办法保存整个用户模型吗?现在,如果我的电话

User.last.save

The cart that I modified is not saved.

我修改的购物车没有保存。

User.last.carts.last.save

Does save the cart.

是否保存购物车。

Is there a way to save all updated attributes of a model?

是否有方法保存模型的所有更新属性?

Thanks

谢谢

2 个解决方案

#1


2  

Saving a model will save any of its associations, but the reason this isn't working for you is because you are re-fetching the User model instead of modifying and saving the same instance.

保存一个模型将会保存它的任何关联,但是这并不适合您,因为您正在重新获取用户模型,而不是修改和保存相同的实例。

user = User.last
user.carts.last.time_purchased = Time.now
user.save

Saving the user should also save the associated cart.

保存用户也应该保存相关的购物车。

#2


2  

This is because you are fetching a copy of the cart, modifying it, then fetching another copy of the cart and saving that.

这是因为您正在获取购物车的副本,修改它,然后获取购物车的另一个副本并保存它。

You should save the cart in a variable, then apply the save on that. For example:

您应该将购物车保存在一个变量中,然后在该变量上应用save。例如:

cart = User.last.carts.last
cart.time_purchased = Time.now
cart.save

Alternatively, you can use update_attribute, like this:

或者,也可以使用update_attribute,如下所示:

User.last.carts.last.update_attribute(:time_purchased, Time.now)

#1


2  

Saving a model will save any of its associations, but the reason this isn't working for you is because you are re-fetching the User model instead of modifying and saving the same instance.

保存一个模型将会保存它的任何关联,但是这并不适合您,因为您正在重新获取用户模型,而不是修改和保存相同的实例。

user = User.last
user.carts.last.time_purchased = Time.now
user.save

Saving the user should also save the associated cart.

保存用户也应该保存相关的购物车。

#2


2  

This is because you are fetching a copy of the cart, modifying it, then fetching another copy of the cart and saving that.

这是因为您正在获取购物车的副本,修改它,然后获取购物车的另一个副本并保存它。

You should save the cart in a variable, then apply the save on that. For example:

您应该将购物车保存在一个变量中,然后在该变量上应用save。例如:

cart = User.last.carts.last
cart.time_purchased = Time.now
cart.save

Alternatively, you can use update_attribute, like this:

或者,也可以使用update_attribute,如下所示:

User.last.carts.last.update_attribute(:time_purchased, Time.now)