belongs_to关联上的named_scope错误

时间:2010-10-01 12:17:08

标签: ruby-on-rails named-scope

我收到了一个named_scope错误,我试图错误地使用它吗?

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>

1 个答案:

答案 0 :(得分:2)

首先,通过Ruby中的约定,以询问标记结尾的方法应该返回true或false。你的named_scope将返回适合的所有者,而不是测试他们的健康状况......我会写一些类似的东西:

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