Tyler DeWitt
Tyler DeWitt

Reputation: 23576

Save All Attributes of Rails Model

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

Upvotes: 3

Views: 314

Answers (2)

Carlos Ramirez III
Carlos Ramirez III

Reputation: 7434

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.

Upvotes: 2

schreifels
schreifels

Reputation: 431

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:

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

Alternatively, you can use update_attribute, like this:

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

Upvotes: 2

Related Questions