Mateu Mateu - 9 months ago 56
Ruby Question

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


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)}

class Child < ApplicationRecord
belongs_to :parent

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)}

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


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

Answer Source

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))}

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

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

See ActiveRecord::SpawnMethods#merge for more information