简体   繁体   English

Rails 4堆栈级别太深错误

[英]Rails 4 Stack level too deep Error

I'm creating a marketplace app where sellers can list items to sell. 我正在创建一个市场应用程序,卖家可以在其中列出要出售的物品。 I want to create a category dropdown so customers can select a category to shop. 我想创建一个类别下拉列表,以便客户可以选择要购物的类别。

In my listing model, I have a 'category' field. 在我的列表模型中,我有一个“类别”字段。 When a user selects a category, I want the view to filter listings from that category. 当用户选择类别时,我希望视图从该类别中筛选列表。

In my routes.rb: 在我的routes.rb中:

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

To create the category menu - in my index.html.erb: 要创建类别菜单-在我的index.html.erb中:

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

In my listings controller: 在我的列表控制器中:

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

category.html.erb: category.html.erb:

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

The homepage category menu shows up. 显示首页类别菜单。 The routes are created. 路由已创建。 But when I click on the category, the url such as listings/c/necklaces gives me the stack level too deep error. 但是当我单击类别时,诸如listings / c / necklaces之类的URL给了我堆栈级别太深的错误。

FYI "Stack Level Too Deep" basically means you have an infinite loop in your code somewhere 仅供参考,“堆栈级别太深”意味着您的代码在某个地方存在无限循环

-- -

From what I can see, the error will be here: 从我所看到的,错误将在这里:

def category
    @category = category

With this code, you're basically invoking the category method again, which in turn will invoke the category method etc, in a never-ending cycle. 使用此代码,您基本上是在再次调用category方法,而后者又将以无休止的循环调用category方法等。 This will prevent your application from being able to run without reloading itself in infinite recursion. 这将阻止您的应用程序在无限递归的情况下重新加载自身而无法运行。

You should change it to: 您应该将其更改为:

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

However, a much more refined way would be: 但是,一种更完善的方法是:

#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