我正在做我的第一个关于铁路项目的红宝石,并且显示“ nil:NilClass的未定义方法'title'”错误。
这是密码
============ index.html.erb =======
<table>
<% @products.select {|p| p.price.to_i > 200 }.each do |product|%>
<tr>
<td><%= product.title %></td>
<td><%= product.price %></td>
</tr>
<% end %>
</table>
============= products_controller.rb =========
class ProductsController < ApplicationController
def index
@products = Product.all
end
def show
if params[:id] == "ALL"
@products = Product.all
else
@product = Product.find(params[:id])
end
Prefix Verb URI Pattern Controller#Action
welcome_index GET /welcome/index(.:format) welcome#index
products GET /products(.:format) products#index
POST /products(.:format) products#create
new_product GET /products/new(.:format) products#new
edit_product GET /products/:id/edit(.:format) products#edit
product GET /products/:id(.:format) products#show
PATCH /products/:id(.:format) products#update
PUT /products/:id(.:format) products#update
DELETE /products/:id(.:format) products#destroy
root GET / welcome#index
=============
我要做的就是如果参数为“ ALL”则显示所有产品,如果参数为“ ONSALE”则显示某些产品(价格<50),以及当参数为产品ID时显示单个产品。欢迎任何建议!
答案 0 :(得分:0)
如果我阅读了您的源代码,似乎您只需要列出价格高于200的产品 您可以使用 where 进行操作,稍后,如果您想更进一步地过滤数据,则可以学习ransack gem
为您的 index.html.erb
<table>
<% @products.each do |product| %>
<tr>
<td><%= product.title %></td>
<td><%= product.price %></td>
</tr>
<% end %>
</table>
这是您的 ProductsController
class ProductsController < ApplicationController
def index
# if you want directly to filter just the list product that has price above 200
# then you can use where, your view just to show the result of @products
@products = Product.where('price > ?',200)
end
end