Written by Katherine Giron Pe
on
on
Why You Have To Use Named Scopes for Rails 3
It’s strange for me to write something that disputes my post earlier. I just spent an hour trying to fix “stack level too deep” error. Only to find out that it has to do with named scopes.
Here’s the problem. I have a class called Food (not really food but since I’m hungry it’s all I could think of right now). Food has many food types.
This was wrong:
class Food < ActiveRecord::Base
def self.kids
where(food_type_id: 1)
end
def self.pets
where(food_type_id: 2)
end
end
I got stack level too deep error. Calling Food.all also didn’t work. Puzzling right? I’m using Rails 3.0.3.
This worked however:
class Food < ActiveRecord::Base
scope :kids, where(food_type_id: 1)
scope :pets, where(food_type_id: 2)
scope :expired, conditions: ["expiration_date <= ?", Time.current]
end
So it works now. But I have no idea why.
Food.kids.expired
Update: The issue with the method is now fixed.