Mateu Mateu - 20 days ago 7
Ruby Question

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

Problem



Lets say I have two Models with a has_many-belongs_to relation. The has_many has a scope defined and an integer attribute named 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


I want to create an scope on the child model, that uses the scope of the parent model.

Is there anyhow so that I can use the definition of scope on Parent?

Current solution



The way I'm doing it right now is

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


However, I'm copying the where clause in both places.

Question



Is there anyhow to call the Parent scope from the child model?

Answer

If you are just looking to merge in the scope then

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

should handle this for you. The SQL generated will be similar to

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

See ActiveRecord::SpawnMethods#merge for more information

Comments