Daniel Rikowski
Daniel Rikowski

Reputation: 72514

How can I keep multiple ActiveRecord instances of the same database row in sync?

In my Rails application I have these models

Order has_many OrderItem
OrderItem belongs_to Order

My controller has this (pseudo) code:

#before_filter
@cart = Order.find(session[:cart_id])

#Action: update_item
item = OrderItem.find(params[:item_id] 
#The order, item belongs to, is in fact @cart, i.e. @cart.id == item.order.id
item.price = 999.99
item.order.total += item.price

After the last line the @cart object still has the old total value.

What's the best way to solve such situations in Rails? I guess the simplest way would be to just reload @cart but perhaps there's a more Rails-like way.

Upvotes: 2

Views: 184

Answers (1)

Samuel Chandra
Samuel Chandra

Reputation: 1185

Did you save the item before getting the total from @cart

item = OrderItem.find(params[:item_id])
item.price = 999.99
item.save!

And to get the total from item's order can be:

total_price = item.order.order_items.sum(&:price)

I am assuming the relationship between Order and OrderItem is

class Order
has_many :order_items
...
end

class OrderItem
belongs_to :order
...
end

The @cart can be reloaded as follow

@cart.reload

OR to get the updated total

@cart.reload.order_items.sum(&:price)

Hopefuly it helps

Upvotes: 3

Related Questions