繁体   English   中英

Rails 4堆栈级别太深错误

[英]Rails 4 Stack level too deep Error

我正在创建一个市场应用程序,卖家可以在其中列出要出售的物品。 我想创建一个类别下拉列表,以便客户可以选择要购物的类别。

在我的列表模型中,我有一个“类别”字段。 当用户选择类别时,我希望视图从该类别中筛选列表。

在我的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 %>

显示首页类别菜单。 路由已创建。 但是当我单击类别时,诸如listings / c / necklaces之类的URL给了我堆栈级别太深的错误。

仅供参考,“堆栈级别太深”意味着您的代码在某个地方存在无限循环

-

从我所看到的,错误将在这里:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM