giovaZ giovaZ - 1 month ago 6
Ruby Question

Rails missing parameters id=> nil

In my ruby on rails application i've got a partial called _cart.html.erb

<h2>Your Cart</h2>
<table>

<%= render(cart.line_items) %>

<tr class="total_line">
<td colspan="2">Total</td>
<td class="total_cell"><%= number_to_currency(cart.total_price) %></td>
</tr>

</table>

<%= button_to 'Checkout', new_order_path, method: :get %>
<%= button_to 'Empty cart', cart, method: :delete,
data: { confirm: 'Are you sure?' } %>


if a cart have one or more line_items i can place an order, in the carts controller I check if the cart have some line_items:

class OrdersController < ApplicationController
include CurrentCart
before_action :set_cart, only: [:new, :create]
before_action :set_order, only: [:show, :edit, :update, :destroy]

# GET /orders/new

def new
if @cart.line_items.empty?
redirect_to store_url, notice: "Your cart is empty"
return
end

@order = Order.new
end
# POST /orders
# POST /orders.json
def create
@order = Order.new(order_params)
@order.add_line_items_from_cart(@cart)

respond_to do |format|
if @order.save
format.html { redirect_to @order, notice: 'Order was successfully created.' }
format.json { render :show, status: :created, location: @order }
else
format.html { render :new }
format.json { render json: @order.errors, status: :unprocessable_entity }
end
end
end
end


where the module CurrentCart is

module CurrentCart
extend ActiveSupport::Concern

private

def set_cart
@cart = Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
@cart = Cart.create
session[:cart_id] = @cart.id
end
end


and the model
Order
is:

class Order < ActiveRecord::Base
has_many :line_items, dependent: :destroy

PAYMENT_TYPES = ["Check", "Credit Card", "Purchase order"]

validates :name, :address, :email, presence: true
validates :pay_type, inclusion: PAYMENT_TYPES

def add_line_items_from_cart(cart)
cart.line_items.each do |item|
item.cart.id = nil
line_items << item
end
end
end


during the validation if i set all the Order's fields blank i recive this error (this output is from the server's console log):

ActionView::Template::Error (No route matches {:action=>"show", :controller=>"carts", :id=>nil} missing required keys: [:id]):
11: </table>
12:
13: <%= button_to 'Checkout', new_order_path, method: :get %>
14: <%= button_to 'Empty cart', cart, method: :delete,
15: data: { confirm: 'Are you sure?' } %>


it seems i miss the parameter :id during the validation. the web output highlight the <%= button_to 'Empty cart', cart, method: :delete, data: { confirm: 'Are you sure' } %> string.

i don't know why the application lose this parameter.
All the help and tips will be appreciated.

Answer

It seems like you need params cart_id in your show page. You have to add in your before_filter

before_action :set_cart, only: [:show, :new, :create]
Comments