My first question here.
I am developing a shopping cart based on “Beginning Ruby on Rails E-
Commerce”.
I would like to be able to add multiple items. Because, what if I
wanted 700 items? I don’t really want to repeat clicking on add or
dragging it to the cart.
I think the best thing (maybe) would be to add a text box in the cart
for item.amount but I’m not sure how to do this and I’m worried I’ll
mess up the code.
Any ideas?
Please please help.
My cart.rb model:
def total
cart_items.inject(0) {|sum, n| n.price * n.amount + sum}
end
def add(product_id)
items = cart_items.find_all_by_product_id(product_id)
product = Product.find(product_id)
if items.size < 1
ci = cart_items.create(:product_id => product_id,
:amount => 1,
:price => product.price)
else
ci = items.first
ci.update_attribute(:amount, ci.amount + 1)
end
ci
end
def remove(product_id)
ci = cart_items.find_by_product_id(product_id)
if ci.amount > 1
ci.update_attribute(:amount, ci.amount - 1)
else
CartItem.destroy(ci.id)
end
return ci
end
My cart_controller.rb has:
def add
params[:id].gsub!(/product_/, “”)
@product = Product.find(params[:id])
if request.xhr?
@item = @cart.add(params[:id])
flash.now[:cart_notice] = “Added #{@item.product.title}</
em>”
render :action => “add_with_ajax”
elsif request.post?
@item = @cart.add(params[:id])
flash[:cart_notice] = “Added #{@item.product.title}”
redirect_to :controller => “catalog”
else
render
end
end
my _cart.rhtml view has:
-
<% for item in @cart.cart_items %>
- <%= render :partial => "cart/item", :object => item %> <% end %>
add_with_ajax.rjs:
page.replace_html “shopping_cart”, :partial => “cart”
page.visual_effect :highlight,
“cart_item_#{@item.product.id}”, :duration => 3
page.visual_effect :fade, ‘cart_notice’, :duration => 3
add.rhtml:
Please confirm adding <%= @product.title %>
to your shopping cart.
<%= button_to “Confirm”, :action => “add”, :id => params[:id] %>
Thanks,
Elle