views:

29

answers:

1

I am getting a named_scope error, am i trying to use it incorrectly?

class Owner < ActiveRecord::Base
  has_many :dogs

  named_scope :is_fit?, :conditions => { :age => 16..40 }
end

class Dog < ActiveRecord::Base
  belongs_to :owner

  def is_owner_fit?
    owner.is_fit?
  end

end

undefined method `is_fit?' for #<ActiveRecord::Associations::BelongsToAssociation:0x251807c>
+2  A: 

First of all, by conventions in Ruby, methods ending with an interrogation mark should return either true or false. Your named_scope will return owners that are fit, and not test for their fitness… I would write something like:

class Owner < ActiveRecord::Base
  has_many :dogs
  FIT_RANGE = (16..40)

  named_scope :fit, :conditions => ["owners.age IN (?)", FIT_RANGE.to_a]

  def is_fit?
    FIT_RANGE.include?(age)
  end
end

class Dog < ActiveRecord::Base
  belongs_to :owner

  def is_owner_fit?
    owner.is_fit?
  end

end
Yannis
Thanks Yannis, a couple of further questions i have. Firstly, in your example, the named scope doesn't seem to be used. Secondly, when i originally had this problem, i used a method like you have above, but then i had a need to work out if there were any fit owners from a collection of owners, e.g owners.is_fit.exists? so i thought i would use a named_scope. I would like the logic of whether the owner is fit or not to exist in one place, so i don't want to do a named_scope and a method.
pingu
I just switch to use a constant as the ages range. It is the set in only one place. You might or not use the fit named_scope to retrieve owners that are fit from the DB.
Yannis