gpt4 book ai didi

ruby-on-rails-3 - 使用目标的范围作为关联条件

转载 作者:行者123 更新时间:2023-12-01 06:39:26 24 4
gpt4 key购买 nike

我有这样的模型

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 的范围作为关联的条件,或以其他任何方式来解决问题?

最佳答案

将 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

关于ruby-on-rails-3 - 使用目标的范围作为关联条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12263607/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com