Rails缺少参数id =>零

时间:2015-09-18 08:39:21

标签: ruby-on-rails ruby

在我的ruby on rails应用程序中,我有一个名为_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?' } %>

如果购物车有一个或多个line_items我可以下订单,在购物车控制器中我会检查购物车是否有一些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

模块CurrentCart是

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

,模型Order是:

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

在验证过程中,如果我将所有订单的字段设置为空白,我会发现此错误(此输出来自服务器的控制台日志):

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?' } %>

似乎我在验证过程中错过了参数:id。网络输出突出显示&lt;%= button_to'清空购物车',购物车,方法::删除,数据:{确认:'您确定'}%&gt;字符串。

我不知道为什么应用程序会丢失此参数。 所有的帮助和提示将不胜感激。

1 个答案:

答案 0 :(得分:1)

您的节目页中似乎需要参数cart_id。您必须添加before_filter

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