4

我有像

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

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

(您可能会猜到,该项目正在移植旧应用程序并且它继承了旧模式)

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

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

4

1 回答 1

0

将 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
于 2013-04-13T05:18:59.743 回答