Ruby on rails 如何通过与多个作用域的关联消除同一个表中的多个联接?
考虑到以下模型和关联:Ruby on rails 如何通过与多个作用域的关联消除同一个表中的多个联接?,ruby-on-rails,ruby-on-rails-3,ruby-on-rails-3.2,Ruby On Rails,Ruby On Rails 3,Ruby On Rails 3.2,考虑到以下模型和关联: class Employee has_many :positions has_many :titles, :through => :positions scope :is_active, -> { joins(:positions).merge(Position.is_active) } scope :title_is, ->(name) { joins(:titles).merge(Title.id_or_name_is(nam
class Employee
has_many :positions
has_many :titles, :through => :positions
scope :is_active, -> { joins(:positions).merge(Position.is_active) }
scope :title_is, ->(name) { joins(:titles).merge(Title.id_or_name_is(name)) }
end
class Position
belongs_to :employee
belongs_to :title
# bool 'active' to indicate whether the position is active or not
scope :is_active, -> { where("active = true") }
end
class Title
has_many :positions
has_many :employees, :through => :positions
scope :id_or_name_is, ->(id_or_name) { where("titles.id = ? OR titles.name = ?", id_or_name, id_or_name) if id_or_name}
end
Employee.is\u active
返回正确数量的结果并生成正确的查询。但是,当我尝试执行Employee.title\u时为(123).是否处于活动状态
(我想返回title\u id
为123且处于活动状态的所有员工,这会导致与职位的多个联接。这没有问题,只是“是活动的”检查仅适用于其中一个职位联接,从而导致活动职位和非活动职位:
SELECT COUNT(*)
FROM `employees`
INNER JOIN `positions` ON `positions`.`employee_id` = `employees`.`id`
INNER JOIN `positions` `positions_employees_join` ON positions_employees_join`.`employee_id` = `employees`.`id`
INNER JOIN `titles` ON titles`.`id` = `positions_employees_join`.`title_id`
WHERE positions.active = true)
AND (titles.id = 123 OR
titles.name = 123)
我还应该注意到,从技术上讲,如果我也有办法在where子句中添加
positions\u employees\u join.active=true
,那么它也会正常工作,尽管我不知道在我的范围内如何做。我会跳过title\u is
范围中的titles
关联
scope :title_is, ->(name) { joins(:positions => :title).merge(Title.is_or_name_is(name)) }
保持关联,因为在调用employee\u instance.titles
而不是employee\u instance.positions.titles
时,它仍然可以提供更高效的查询
但就您的作用域而言,执行
联接(:positions=>:title)
会告诉ActiveRecord您希望使用来自调用联接(:positions)的其他作用域的常规联接
哎哟。我的错。我没有仔细查看您在职位
模型中的关联。我已更新了答案以反映您的评论。谢谢:)