【问题标题】:named_scope error on belongs_to associationbelongs_to 关联上的 named_scope 错误
【发布时间】:2010-10-01 12:17:07
【问题描述】:

我收到了一个 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>

【问题讨论】:

    标签: ruby-on-rails named-scope


    【解决方案1】:

    首先,按照 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
    

    【讨论】:

    • 谢谢 Yannis,我还有几个问题。首先,在您的示例中,似乎没有使用命名范围。其次,当我最初遇到这个问题时,我使用了像你上面那样的方法,但后来我需要从所有者集合中确定是否有合适的所有者,例如 owner.is_fit.exists?所以我想我会使用一个named_scope。我希望所有者是否适合的逻辑存在于一个地方,所以我不想做一个 named_scope 和一个方法。
    • 我只是切换到使用一个常数作为年龄范围。是只在一处的安排。您可能会或不会使用 fit named_scope 从数据库中检索适合的所有者。
    猜你喜欢
    • 1970-01-01
    • 2011-06-22
    • 1970-01-01
    • 1970-01-01
    • 2019-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多