Reputation: 4526
I'm implementing this shopping cart gem, but having problems when I add the item to cart in the controller. I tried executing the code using rails console
and it works fine. Not sure why I'm getting this error from the controller.
helper_method :add_to_cart
def add_to_cart
@cart = session[:active_cart]
@product = Product.find(params[:product_id])
@cart.add(@product, 99.99)
end
post '/add_to_cart/:product_id' => 'products#add_to_cart', :as => 'add_to_cart'
<% products.each do |product| %>
<%= button_to "Add to Cart", add_to_cart_path(:product_id => product.id), :method => :post %>
<a href="<%= addresses_path(:brand => product.brand.id, :product_id => product.id) %>" class="list-group-item">
<%= image_tag product.image.url(:square), class: "product-list-group-item" %>
<%= product.name %>
<span class="badge">$<%= number_with_precision(product.price, precision: 2) %></span>
</a>
<% end %>
Upvotes: 2
Views: 902
Reputation: 34338
@cart = session[:active_cart]
this is returning a hash and that's why you get the mentioned error when you call this:
@cart.add(@product, 99.99)
Because there is no add
method implemented for hash object.
I suggest you to inspect the @cart
object in your controller like this:
@cart = session[:active_cart]
puts @cart.inspect
puts @cart.class
and then you will see, it's a hash object and you should be able to extract the required cart
object from that hash.
The main issue is to get the correct @cart
object from the session. Once you do that, then, it should work :)
Upvotes: 2