I’m trying to calculate a total price for all the items contained within a cart. However I’m getting a undefined method total_cart_price for ActiveRecord::Relation:xxx
Shop Cart Model (shop_cart.rb)
has_many :shop_cart_items, :dependent => :destroy
def total_cart_price
shop_cart_items.to_a.sum { |item| item.total_price }
end
Shop Cart Item Model (shop_cart_item.rb)
attr_accessible :quantity, :shop_cart_id, :shop_product_id
belongs_to :shop_product
belongs_to :shop_cart
def total_price
shop_product.sell * quantity
end
Basket View (shop/basket.html.erb)
<tbody>
<% @cart_items.each do |item| %>
<tr>
<td><%= item.shop_product.name %></td>
<td><%= number_to_currency(item.shop_product.sell) %></td>
<td><%= item.quantity %></td>
<td><%= number_to_currency(item.total_price) %></td>
</tr>
<% end %>
<tr>
<td></td>
<td></td>
<td>Subtotal:</td>
<td><%= number_to_currency(@cart_items.total_cart_price) %></td>
</tr>
</tbody>
The total price, for a single item, works fine; the error is trying to calculate a sum of all the items.
I do not have a shop_cart controller or views as I am calling the methods from a shop#basket view – not sure if this is what is causing the problem?
Any help much appreciated.
Try this,
@cart_items.shop_cart.total_cart_priceit’s a cart method.