将 belongs_to 关联的范围用于第一个模型中的范围 - Ruby on Rails

Use scope of a belongs_to association to scope in the first model - Ruby on Rails

问题

假设我有两个具有 has_many-belongs_to 关系的模型。 has_many 定义了一个范围和一个名为 grade 的整数属性。

class Parent < ApplicationRecord
  has_many :children
  scope :great, -> (min_grade) {where("grade > :grade", grade: min_grade)}
end

class Child < ApplicationRecord
  belongs_to :parent
end

我想在子模型上创建一个范围,它使用父模型的范围。

有没有办法让我可以在 Parent 上使用范围定义?

当前解决方案

我现在的做法是

class Child < ApplicationRecord
  belongs_to :parent
  scope :wit_great_parent, -> (min_grade) {
        join(:parent).where("grade > :grade", grade: min_grade)}
end

但是,我在两个地方都复制了 where 子句。

问题

有没有办法从子模型调用父作用域?

嗯,也许,您只需要在 Child 范围内的 grade > :grade 查询之前放置 parents.。你拼错了 joins 方法。

尝试像这样在子模型上使用范围:

class Child < ApplicationRecord
  belongs_to :parent
  scope :wit_great_parent, -> (min_grade) {
        joins(:parent).where("parents.grade > :grade", grade: min_grade)
  }
end

如果您只是想在范围内合并,那么

class Child < ApplicationRecord
  belongs_to :parent
  scope :with_great_parent, -> (min_grade) {joins(:parent).merge(Parent.great(min_grade))}
end

应该会为您处理。生成的 SQL 将类似于

SELECT * 
FROM children 
  INNER JOIN parents ON children.parent_id = parents.id
WHERE 
  parents.grade > --Whatever value you pass as min_grade

有关详细信息,请参阅 ActiveRecord::SpawnMethods#merge