Topic: Adding many items to a cart instead of one at a time.

I have Leads which are added to a Cart as LineItems in the Cart.

In my leads index a user has a button for "buy now":

<%= button_to 'Add to Cart', line_items_path(lead_id: lead) %>

this maps to the line_items_controller#create action:

def create
    @cart = current_cart
    lead = Lead.find(params[:lead_id])
    @line_item = @cart.line_items.build(lead: lead)
    
    respond_to do |format|
      if @line_item.save
        format.html {redirect_to @line_item.cart, notice: "Lead successfully added to cart."}
      else
        format.html {redirect_to leads_path, error: "Lead not added to cart."}
      end 
    end 
  end 

I want to refactor this so that the user can check a checkbox next to the leads he.she wants to buy and then click an add to cart that adds all checked leads to the cart as individual line items.

Re: Adding many items to a cart instead of one at a time.

Did you watched this screencast yet ?
http://railscasts.com/episodes/52-updat … checkboxes
I think this will answer your question.

Re: Adding many items to a cart instead of one at a time.

That gets me going in the right direction especially for the views.  Any ideas how to update my create action:

def create
    @cart = current_cart
    lead = Lead.find(params[:lead_id])
    @line_item = @cart.line_items.build(lead: lead)
    
    respond_to do |format|
      if @line_item.save
        format.html {redirect_to @line_item.cart, notice: "Lead successfully added to cart."}
      else
        format.html {redirect_to leads_path, error: "Lead not added to cart."}
      end 
    end 
  end 

I think I would need to pass in params[:lead_ids] but it has to create a new line item as well. Just not sure how to get this done.

Re: Adding many items to a cart instead of one at a time.

You can loop through params[:lead_id] and build the line items. Because you add the line items to your card you have to save your cart.

   
   
  def create
    @cart = current_cart
    params[:lead_ids].each do |lead_id|
      @card.line_items.build(lead: Lead.find(lead_id))
    end
    
    respond_to do |format|
      if @cart.save
        format.html {redirect_to @line_item.cart, notice: "Lead successfully added to cart."}
      else
        format.html {redirect_to leads_path, error: "Lead not added to cart."}
      end 
    end 
  end

This could work I think

Re: Adding many items to a cart instead of one at a time.

ahh that make sense.