Preserve all attributes of the Rails model

I have a user model that has a lot of carts

class User < ActiveRecord::Base
  has_many :carts


If I update the cart:

User.last.carts.last.time_purchased =


Is there a way to keep the entire user model? Now if I call


The cart that I changed is not saved.


Saves the cart.

Is there a way to keep all the updated attributes of the model?



source to share

2 answers

Saving a model will preserve any of its associations, but the reason it doesn't work for you is because you are reselecting the model User

instead of changing and saving the same instance.

user = User.last
user.carts.last.time_purchased =


Saving the user should also save the linked cart.



This is because you checkout a copy of the cart, modify it, then check out another copy of the cart and save it.

You have to save the cart to a variable and then apply the save to it. For example:

cart = User.last.carts.last
cart.time_purchased =


Alternatively, you can use update_attribute like:





All Articles