[英]Error undefined method `+' for nil:NilClass // Ruby on Rails
[英]Ruby on Rails error: undefined method for nil:NilClass
我正在铁路项目上做我的第一个红宝石,并且对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时显示单个产品。 任何建议都欢迎!
如果我阅读了您的源代码,似乎您只需要列出价格在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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.