2014-08-30 64 views
0

我正在創建一個市場應用程序,賣家可以列出要銷售的物品。我想創建一個類別下拉菜單,以便客戶可以選擇一個類別進行購物。Rails 4堆棧級別太深Error

在我的列表模型中,我有一個'category'字段。當用戶選擇一個類別時,我希望該視圖能夠過濾來自該類別的列表。

在我的routes.rb:

get '/listings/c/:category' => 'listings#category', as: 'category' 

要創建類別菜單 - 在我index.html.erb:

<%= Listing.uniq.pluck(:category).each do |category| %> 
    <%= link_to category, category_path(category: category) %> 
<% end %> 

在我的列表控制器:

def category 
    @category = category 
    @listings = Listing.not_expired.where(:category => @category) 
    end 

category.html.erb:

<% @listings.each do |listing| %> 
     #some html 
<% end %> 

顯示主頁類別菜單。路線已創建。但是當我點擊這個類別時,諸如listing/c/necklaces這樣的URL會給我帶來太深的錯誤。

回答

2

FYI「堆棧級別太深」基本上意味着你有一個無限循環在你的代碼的某個地方

-

從我所看到的,誤差會在這裏:

def category 
    @category = category 

使用此代碼,您基本上再次調用category方法,這反過來會在永無止境的循環中調用category方法等。這將阻止您的應用程序無需重新加載無限遞歸即可運行。

您應將其更改爲:

def category 
    @category = params[:category] 
    @listings = Listing.not_expired.where(:category => @category) 
    end 

然而,更加精細的方法是:

#app/models/category.rb 
class Category < ActiveRecord::Base 
    has_many :listings do 
     def not_available 
     #your not available method here 
     end 
    end 
end 

#app/models/listing.rb 
class Listing < ActiveRecord::Base 
    belongs_to :category 
end 

#app/controllers/your_controller.rb 
def category 
    @category = Category.find params[:categpry] 
    @listings = @category.listings.not_available