我编写了一个控制器和模型来从db获取数据。但它显示我们运行rails时的错误是:ProductsController中的NameError#url中的索引..我将我的url作为localhost:3000 /产品。然后它给出错误:
NameError in ProductsController#index
uninitialized constant ProductsController::Product.
my controller is:
products_controller.rb
class ProductsController < ApplicationController
# GET /products
# GET /products.json
def index
@products = Product.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @products }
end
end
#render :text => params and return false
# GET /products/PR1
# GET /products/PR1.json
def show
@product = Product.find(params[:prod_id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @product }
end
end
end
model as product.rb
class Product < ActiveRecord::Base
attr_accessible :model_name, :brand_name, :price, :discount, :qty_available
end
我在routes.rb中声明为: 资源:产品
我设计了index.html.erb和show.html.erb
我不知道错误在哪里......
答案 0 :(得分:2)
型号名称为product.rb
而不是products.rb
,在您的show动作中,您需要一个产品,因此正确的语法是:
def show
@product = Product.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @product }
end
end
答案 1 :(得分:0)
使用find_by_id而不是find。每当找不到记录时,它会抛出异常ActiveRecord :: RecordNotFound,而find_by_id会返回nil