堆栈级别太深错误 - 此代码有什么问题?

时间:2015-02-16 16:59:49

标签: ruby-on-rails ruby methods stack-overflow infinite-loop

我在使用的控制器中有一些重复的代码,我认为我会将其放入方法中。但是,这样做会导致堆栈级别太深而且“#”;错误。我明白这意味着那里有一个无限循环,虽然我无法看到它(我对此非常陌生)!

这里有适用的控制器代码,但不是干:

def cuisine
    if params[:cuisine].present?
      @recipes = Recipe.all.includes(:cuisines).where(cuisines: { name: params[:cuisine].humanize })
    end
    @message = "There are no recipes matching this cuisine. Please return to" if @recipes.empty?
    @user = current_user
    @count = @recipes.count
  end

  def category
    if params[:category].present?
      @recipes = Recipe.all.includes(:categories).where(categories: { name: params[:category].humanize })
    end
    @message = "There are no recipes matching this category. Please return to" if @recipes.empty?
    @user = current_user
    @count = @recipes.count
  end

我以为我可以将代码更改为此代码,不过它会引发错误:

def category
  category_setter(category)
end

def cuisine
  category_setter(cuisine)
end

private

    def category_setter(c)
      @user = current_user
      @count = @recipes.count
      sym = c.to_sym
      syms = c.pluralize.to_sym
      if params[sym].present?
        @recipes = Recipe.all.includes(syms).where(syms: { name: params[sym].to_s.humanize })
      end
      @message = "There are no recipes matching this #{sym}. Please return to" if @recipes.empty?
    end

在视图中显示如下:

<div>
      <% @recipes.each do |recipe| %>
        <% if ingredient_matcher(@user, recipe)  %>
          </br><strong><%= recipe.name %></strong>
              <ul>
                <% recipe.ingredients.each do |ing| %>
                  <li><%= ing.name.humanize %></li>
                <% end %>
              </ul>
              <p><%= recipe.method %></p>
        <% else %>
          <% @count -= 1  %>
        <% end %> 
      <% end %>
</div>

使用此辅助方法:

def ingredient_matcher(one, two)
    (one.fridge.ingredients.pluck(:id) & two.ingredients.pluck(:id)) == two.ingredients.pluck(:id)
  end

希望有人能够对此有所了解所需的所有代码 - 我认为这将是一件非常简单的事情我错过了!

先谢谢,史蒂夫。

1 个答案:

答案 0 :(得分:1)

你在这里引起无限递归:

def category
  category_setter(category)
end

在这里:

def cuisine
  category_setter(cuisine)
end

不要传递方法名,而是调用你的setter方法传递一个String:

category_setter('category')

并且

category_setter('cuisine')