希望這是一個很容易解決的問題,因爲我剛剛開始使用Rails。Rails錯誤「NoMethodError」 - 剛開始使用Rails
我有一個數據庫(產品),其中包含許多產品屬性,包括品牌,顏色和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#索引(while試圖做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索引中定義問題?如果是這樣,這怎麼辦?
您的時間
數據庫沒有被過濾,每個查詢都是單獨的和單獨的。將@distinctbrands查詢替換爲以下內容會發生什麼情況:@distinctbrands = ['a','b']。你仍然得到同樣的錯誤? – 2011-02-15 00:18:13