问题
假设我有两个具有 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 子句。
问题
有没有办法从子模型中调用父作用域?
最佳答案
如果你只是想在范围内合并,那么
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
了解更多信息
关于ruby-on-rails - 在第一个模型中使用 belongs_to 关联的范围 - Ruby on Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40593850/