类别#show中的NameError

时间:2016-06-12 18:13:01

标签: ruby-on-rails ruby ruby-on-rails-4 model-view-controller

所以我的rails应用程序中有产品和购物车系统。现在,我尝试在自定义控制器下创建自定义页面,以展示特定类别的每个产品。当我将form_for包含到产品的div类中时(为了提交表单并将产品移动到购物车中),我收到此错误:

Showing /home/ubuntu/workspace/app/views/categories/show.html.erb where line #28 raised:

undefined local variable or method `order_item' for #<#<Class:0x007fd83dfbdea8>:0x007fd85cbad0b0>
Did you mean?  order_item_url

这是在app / views / categories / show.html.erb上显示错误的表单:

<%= form_for order_item, remote: true do |f| %>
      <h4 class="text-right">Unit Price: <span style="color: green"><%= number_to_currency product.price %></span></h4>
        <div class="input-group">
          <%= f.number_field :quantity, value: 1, class: "form-control", min: 1 %>
          <div class="input-group-btn">
            <%= f.hidden_field :product_id, value: product.id %>
            <%= f.submit "Add to Cart", class: "btn btn-primary" %>
          </div>
        </div>
      <% end %>

这些是我的控制者:

class ProductsController < ApplicationController
  def index
    @products = Product.all
    @order_item = current_order.order_items.new
  end

  def new
    @product = Product.new @categories = Category.all.map{|c| [ c.name, c.id ] }
  end


  def create 
   @product = Product.new(product_params) 
   @product.category_id = params[:category_id] 
   respond_to do |format| 
   if @product.save 

      format.json { render :show, status: :created, location: @product } 
   else 
       format.html { render :new } 
       format.json { render json: @product.errors, status: :unprocessable_entity } 
   end 
  end 
end

def edit
  @categories = Category.all.map{|c| [ c.name, c.id ] }
end

def update 
  @product.category_id = params[:category_id]
end


end

order_items_controller.rb:

class OrderItemsController < ApplicationController
  def create
    @order = current_order
    @order_item = @order.order_items.new(order_item_params)
    @order.user_id = current_user.id
    @order.save
    session[:order_id] = @order.id
  end



  def update
    @order = current_order
    @order_item = @order.order_items.find(params[:id])
    @order_item.update_attributes(order_item_params)
    @order_items = @order.order_items
  end



  def destroy
    @order = current_order
    @order_item = @order.order_items.find(params[:id])
    @order_item.destroy
    @order_items = @order.order_items
  end
private
  def order_item_params
    params.require(:order_item).permit(:quantity, :product_id, :user_id)
  end
end

及相关路线:

Rails.application.routes.draw do

  resources :categories
  resources :products, only: [:index]
  resource :cart, only: [:show]
  resources :order_items, only: [:create, :update, :destroy, :new]
  root to: "products#index"

1 个答案:

答案 0 :(得分:1)

您处于属于类别控制器的视图中。

您需要在类别控制器的show动作中添加:

# CategoriesController
def show
 @order_item = OrderItem.new # Add this line
 # rest of your code
end

并在form_for order_item中替换@order_item