Reputation: 25542
I have a simple cart system that I have been working on for a little while for an application and am needing a little help in trying to figure out how to update a particular attribute in a join table (Between Order and Products).
Here is the code:
def add_product_to_cart
@product = Product.by_client(current_client).first
@order = current_order
unless @order.products.exists? :id => @product.id
@order.products << @product
end
end
I am trying to update a particular attribute when I update the @order.products
...
This is what I am trying to do:
@order.products << @product
--> When this happens I need to update a :price
attribute..
Anyway of doing this?
Upvotes: 1
Views: 297
Reputation: 3462
Desire to put attributes into join table may be a sign of missing model. You can promote join table into model, say OrderItem
, by adding primary key to it. HABTM associations in Order
and Product
then become has_many through
associations. The new model would be a good place for setting up callback which populates price
attribute. It can also unlock additional benefits, like time-stamping items and making them act_as_list
, etc.
Upvotes: 1
Reputation: 3365
class Order
has_many :products
def price
products.sum(:price)
end
end
Just off the top of my head. Here's the sum reference:
http://ar.rubyonrails.org/classes/ActiveRecord/Calculations/ClassMethods.html#M000296
Upvotes: 1