samedi 16 mai 2015

Create new route Rails 4

I have a problem: I want do decrement the quantity of a product of a line_item I use a button_to to decrement the quantity (the cart will be updated by AJAX) Btw , i' m not able to create a new action in the controller of line_items. I created the new action "less" and i added the new route

resources :line_items do
    post :less, on: :member     
end

in the routes.rb file. But it doen't work. i have this error:

ActionController::UrlGenerationError

No route matches {:action=>"less", :controller=>"line_items", :product_id=>7} missing required keys: [:id]

Can you help me? Thx all :)

here my code.

View:

<%= button_to '-', less_line_item_path(product_id: line_item.product_id), remote: true %>

In line_items Controller:

...
def less
    product = Product.find(params[:product_id])
    @line_item = @cart.less_items(product.id)
    respond_to do |format|
  if @line_item.save
    format.html { redirect_to store_url}
            #a respond_to passiamo il blocco con la @current_item
            #si passa un blocco perchè è definito cosi il metodo
            format.js   { @current_item = @line_item} 
    format.json { render :show, status: :created, location: @line_item }
  else
    format.html { render :new }
    format.json { render json: @line_item.errors, status: :unprocessable_entity }
  end
end
end

...

In cart model:

def less_items(product_id)  
    current_item = line_items.find_by(product_id: product_id)
    if current_item && current_item > 1
        current_item.quantity -= 1
    else
        #don't do nothing
    end
    current_item
end

Aucun commentaire:

Enregistrer un commentaire