我正在创建一个市场应用程序,卖家可以在其中列出要出售的商品。我想创建一个类别下拉列表,以便客户可以选择一个类别来购物。
在我的列表模型中,我有一个“类别”字段。当用户选择一个类别时,我希望视图从该类别中筛选列表。
在我的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)
endcategory.html.erb:
<% @listings.each do |listing| %>
#some html
<% end %>将显示主页类别菜单。路线是创建的。但是,当我单击这个类别时,url (如列表/c/项链)给我的堆栈级别带来了太深的错误。
发布于 2014-08-30 08:11:44
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_availablehttps://stackoverflow.com/questions/25580170
复制相似问题