【问题标题】:Use target's scope as a condition of association使用目标的范围作为关联条件
【发布时间】:2012-08-29 02:53:24
【问题描述】:

我有类似的模型

class Employee < ActiveRecord::Base
  belongs_to :branch, :foreign_key => :branch_code, :primary_key => :branch_code,
    :conditions => proc{["? BETWEEN enabled_day AND expiration_day", Date.current]}
end

class Branch < ActiveRecord::Base
  has_many :employees, :foreign_key => :branch_code, :primary_key => :branch_code

  scope :valid, lambda {where(["? BETWEEN enabled_day AND expiration_day", Date.current])}
end

员工属于一个分支(简单),但分支有多个相同branch_code的记录,应该始终使用“此时有效”的记录。

(您可能猜到了,该项目正在移植一个旧应用程序并且它继承了旧架构)

现在,它确实有效,但我必须编写完全相同的 where 条件两次(实际上分支与更多表相关联,所以 5 或 6 次)。

想知道我是否可以使用 Branch 的范围作为关联的条件,或者任何其他方式来干燥?

【问题讨论】:

    标签: ruby-on-rails-3 activerecord scope associations


    【解决方案1】:

    将 has_many_through 与 default_scope 一起使用会起作用吗?

    类似的东西:

    class Employee < ActiveRecord::Base
      has_many :assignments
      has_one :branch, :through => :assignments
    end
    
    class Branch < ActiveRecord::Base
      has_many :assignments
      has_many :employees, :through => :assignments
    end
    
    class EmployeeAssignments < ActiveRecord::Base
      attr_accessible :enabled_day, :expiration_day
    
      belongs_to :employee
      belongs_to :branch
    
      def self.default_scope
        where '? BETWEEN enabled_day AND expiration_day', Date.current
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-13
      • 1970-01-01
      • 1970-01-01
      • 2015-06-25
      • 1970-01-01
      • 1970-01-01
      • 2011-06-19
      相关资源
      最近更新 更多