【发布时间】: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