问题
可以说我有has_many-belongs_to关系的两个模型。 has_many有一个定义的范围和一个名为grade的整数属性。使用范围belongs_to关联范围在第一个模型 - Ruby on Rails
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子句。
问题
有没有办法从子模型调用父范围?
孩子只有一个父母,所以我不认为它使多大意义,范围的单个对象:/也许'回报为零如果parent.grade> min_grade'? – gabrielhilal
我想返回所有拥有更高年级的父母的孩子。我不想让所有的孩子都接受你提出的“如果”一个一个的检查。 – Mateu