使用目标的范围作为关联条件

时间:2012-09-04 12:33:19

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

我有像

这样的模特
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的记录,应始终使用“此时有效”的记录。

(正如您可能猜到的那样,该项目正在移植一个旧应用程序,并且它会成功使用旧架构)

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

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

1 个答案:

答案 0 :(得分: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