Vishal Taj PM
Vishal Taj PM

Reputation: 1359

How to invoke a child models scope from parent in ActiveRecord?

Please help me to find a way to invoke a child scope inside parent scope. is there any way by which i can achieve that.

The scenario is follows:

class Film < ActiveRecord::Base
  ...
  has_many :shows
  scope :active_shows, ->{
    joins(:shows)
  }
  ...
end

class Show < ActiveRecord::Base
  ...
  belongs_to :film
  scope :active_for_now, ->{
   ...
  }
  ...
end

From the above Eg, i want to know how to invoke scope active_for_now from active_shows. show table has fields start_time and end_time when i call Film.active_shows have to get all Films having active show for the current time.

please help me if there any solution for that and please correct if i gone wrong.

Upvotes: 2

Views: 1638

Answers (2)

max
max

Reputation: 101811

You can setup a separate has_many association with a scope:

class Film < ActiveRecord::Base
  has_many :shows
  has_many :active_shows, class_name: 'Show', ->{ Show.active_for_now }
end

The main advantage is that you can use the association directly when joining:

@films = Film.eager_load(:active_shows).find(params[:id])

Upvotes: 3

mccalljt
mccalljt

Reputation: 796

I'm a little confused on the scope and association names and whether they are representing a relationship I'm not seeing but to invoke a scope that is defined on the has_many, you can use #merge

class A < ActiveRecord::Base
  ...
  has_many :bs
  scope :abs, ->{
    joins(:bs).merge(B.bas)
  }
  ...
end

Upvotes: 3

Related Questions