[英]Rails error “NoMethodError” - Just started to use Rails
希望这是一个非常容易解决的问题,因为我刚开始使用Rails。
我有一个数据库(Products),其中包含许多产品属性,包括品牌,颜色和product_type。
我目前有一个索引页面(位于productfinder目录中),该页面可以提供数据库中产品的摘要。 我在index.html.erb中使用以下代码:
<% @distinctbrands.each do |distinctbrand| %>
<h4><%= distinctbrand %></h4>
<% end %>
在productfinder_controller.rb中,我有:
def index
@distinctbrands = Product.find( :all, :order => 'brand ASC', :select => 'brand' ).map{ |i| i.brand }.uniq
@distinctcolours = Product.find( :all, :order => 'colour ASC', :select => 'colour' ).map{ |i| i.colour }.uniq
end
到这一点为止,所有工作都需要正确进行
现在,我想在索引页面上添加3个按钮,这些按钮将使用户能够重新计算产品子集的独特品牌和独特颜色-匹配product_type =“ new”或“ used”。 第三个按钮将对应于根本不被过滤的结果(即,索引页面最初加载时)。
在上一个问题中,建议我添加以下代码:在productfinder_controller中:
before_filter :load_products, :only => [:index, :bybrand, :bycolour, :byprice]
protected
def load_products
@products = Product.by_product_type(params[:product_type])
end
在Product.rb中:
scope :by_product_type, lambda{ |product_type| where(product_type: product_type.to_i) unless product_type.nil? }
在index.html.erb中
<%= link_to "New", :controller => params[:controller], :action => params[:action], :product_type => 'New' %>
<%= link_to "Used", :controller => params[:controller], :action => params[:action], :product_type => 'Used' %>
<%= link_to "Don't Restrict", :controller => params[:controller], :action => params[:action], :product_type => '' %>
现在运行应用程序时,出现NoMethodError-ProductFinder#Index(尝试执行nil.each时,该错误与<%@ distinctbrands.each相关| distinctbrand |%>
我想知道问题是否出在定义@distinctbrands和@distinctcolours的函数上,因为现在已经过滤了数据库,但是在以下两种情况下我都得到了相同的错误:
def index
@distinctbrands = @product.find( :all, :order => 'brand ASC', :select => 'brand' ).map{ |i| i.brand }.uniq
@distinctcolours = @product.find( :all, :order => 'colour ASC', :select => 'colour' ).map{ |i| i.colour }.uniq
end
和
def index
@distinctbrands = Product.find( :all, :order => 'brand ASC', :select => 'brand' ).map{ |i| i.brand }.uniq
@distinctcolours = Product.find( :all, :order => 'colour ASC', :select => 'colour' ).map{ |i| i.colour }.uniq
end
有人可以为我提供可能的解决方案吗? 问题是否与在def索引中未定义@products有关? 如果是这样,该怎么办?
非常感谢您的宝贵时间
使用before_filter,您正在创建@products的实例,但是索引仍在加载@distinctbrands。
我认为您应该做的是:
因此,在您的模型中,load_products方法可能类似于:
def load_products
if params[:product_type]
@products = Product.by_product_type(params[:product_type])
else
@products = Product.find( :all, :order => 'brand ASC', :select => 'brand' ).map{ |i| i.brand }.uniq
end
end
然后在您的索引中更新为:
<% @products.each do |product| %>
<h4><%= product.name %></h4>
<% end %>
我可能会感到困惑,但是我在这里看到了一些不同的东西。 我看到品牌,颜色和类型。 您要显示的默认视图是什么? 如果按类型过滤,颜色何时起作用?
感谢您的所有帮助-我再次听了您的建议,并设法确定product.rb中有一个小错误,现在显示为:
scope :by_product_type, lambda{|product_type| where(:product_type => product_type) unless product_type.nil? }
一切似乎都运作良好! 再次感谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.