【发布时间】:2011-02-15 00:05:46
【问题描述】:
希望这是一个非常容易解决的问题,因为我刚开始使用 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 和 @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 索引中定义有关?如果是这样,如何做到这一点?
非常感谢您的宝贵时间
【问题讨论】:
-
数据库没有被过滤,每个查询都是独立的。当您将 @distinctbrands 查询替换为以下内容时会发生什么:@distinctbrands = ['a', 'b']。你仍然遇到同样的错误吗?
标签: ruby-on-rails ruby-on-rails-3 nomethoderror