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 = Time.now
Is there a way to keep the entire user model? Now if I call
User.last.save
The cart that I changed is not saved.
User.last.carts.last.save
Saves the cart.
Is there a way to keep all the updated attributes of the model?
thank
source to share
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 = Time.now
user.save
Saving the user should also save the linked cart.
source to share
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 = Time.now
cart.save
Alternatively, you can use update_attribute like:
User.last.carts.last.update_attribute(:time_purchased, Time.now)
source to share