问题
假设我有两个模型,它们之间有一个 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
我希望您能在子模型上创建一个作用域,该作用域使用父模型的作用域。是否有任何方法可以使用父级作用域的定义?
当前解决方案
目前我所做的方式是:class Child < ApplicationRecord
belongs_to :parent
scope :wit_great_parent, -> (min_grade) {
join(:parent).where("grade > :grade", grade: min_grade)}
end
然而,在这两个地方我都复制了where子句。
问题
有没有办法从子模型中调用父级作用域?
如果 parent.grade > min_grade,则返回 nil
? - gabrielhilal