希望这是一个非常容易解决的问题,因为我刚开始使用 Rails。
我有一个数据库(产品),其中包含许多产品属性,包括品牌、颜色和产品类型。
我目前有一个索引页面(在 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 个按钮,这些按钮将使用户能够重新计算产品子集的 distinctbrands 和 distinctcolours - 匹配 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 do |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
请问有人可以为我提供一个可能的解决方案吗?问题是否与 @products 未在 def 索引中定义有关?如果是这样,如何做到这一点?
非常感谢您的时间