I've a bit of repeated code in a controller I'm using, which I thought I'd drop into a method. However, doing so raises a 'stack level too deep' error. I understand this means there's an infinite loop in there somewhere, though I can't see it (I'm pretty new to this)!
Here's the controller code that works, though isn't DRY:
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
I thought I could change the code to this, though that's where it's throwing up the error:
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
It's displayed as such in the view:
<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>
Using this helper method:
def ingredient_matcher(one, two)
(one.fridge.ingredients.pluck(:id) & two.ingredients.pluck(:id)) == two.ingredients.pluck(:id)
end
Hope that's all the code needed for someone to be able to shed some light on to this - I'm thinking it'll be something pretty straightforward I'm missing!
Thanks in advance, Steve.
You are causing infinite recursion here:
def category
category_setter(category)
end
and here:
def cuisine
category_setter(cuisine)
end
Instead of passing the method name, call your setter method passing it a String:
category_setter('category')
And
category_setter('cuisine')
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments