【问题标题】:How can I join a has_many association with a scope in Active Record?如何在 Active Record 中加入 has_many 关联和范围?
【发布时间】:2011-11-20 11:14:12
【问题描述】:

这是我的关联和范围设置:

has_many    :owned_products

has_many    :owned_lessons, :through => :owned_products, :source => :lesson, :conditions => "owned_products.product_type = 'Lesson'"

scope :active_purchase_scope, lambda {
    where('owned_products.created_at' => (Date.today - CONFIG['downloads']['time_window'].days)..(Date.today)).order('owned_products.created_at DESC')
}

def active_lessons 
    owned_lessons.active_purchase_scope
end

这是我得到的错误:

ruby-1.8.7-p334 :005 > User.find_by_username('joeblow').active_lessons
NoMethodError: undefined method `active_purchase_scope' for #<User:0x1051a26c8>

【问题讨论】:

    标签: ruby-on-rails activerecord scope associations


    【解决方案1】:

    scope 可以被视为类方法,association 可以被视为实例方法。在您的代码示例中,owned_lessons 方法返回一个数组对象。您不能在数组对象(或用户对象)上调用 active_purchase_scope,因为范围只能在 Model 类上调用(即在您的情况下为 User.active_purchase_scope

    您可以通过在 Lesson 模型上添加范围来解决此问题

    class Lesson
      has_many    :owned_products
    
      scope :active_purchase_scope, lambda {
        include(::owned_products).where('owned_products.created_at' => 
              (Date.today - CONFIG['downloads']['time_window'].days)..(Date.today)).
                order('owned_products.created_at DESC')
      }
    
    end
    

    并重写User类如下:

    class User
    
      has_many    :owned_products
    
      has_many    :owned_lessons, :through => :owned_products, :source => :lesson, 
                     :conditions => "owned_products.product_type = 'Lesson'"
    
    
      def active_lessons 
        owned_lessons.active_purchase_scope
      end
    
    end
    

    owned_lessonsLesson 模型上返回一个匿名作用域,因此我们可以将它与来自同一模型的作用域active_purchase_scope 链接起来。

    【讨论】:

    • 我明白为什么这不起作用(因为 Array 类),但我仍然不知道如何抽象 active_purchase_scope,因为所有产品都需要使用它,而不仅仅是课程。目前我的产品模型没有继承任何东西。我应该尝试创建一个所有产品都继承自的 Product 模型(这可能真的让事情变得混乱,因为我在连接表中有 product_id)还是可以通过 mixin 完成同样的事情?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多