nanounanue
nanounanue

Reputation: 8342

scope for nested has_many relationships

I have a has_many relationship between two objects in Rails, let's say A, B and C

class A < ActiveRecord::Base
  has_many :b
end

class B < ActiveRecord::Base
  belongs_to :a
  has_many :c
end

class C < ActiveRecord::Base
  belongs_to :b
  has_many :d
end

class D < ActiveRecord::Base
  belongs_to :c
end

I want to obtain all the objects of class D, that has a specific c with belongs to an specific B and A . I could make the following scopes

  scope :by_c, ->(cc) { where(:c_id => cc) }

  scope :by_b, lambda { |bb|
    joins(:c).where('c.b_id = ?', bb)
  }

How should I do a scope :by_a ? Is this the best way of doing it?

Upvotes: 2

Views: 300

Answers (1)

bratsche
bratsche

Reputation: 2674

scope :by_a ->(aa) {
  joins(:c).where(c_id: C.joins(:b).where(b_id: B.joins(:a).where(a_id: aa.id)))
}

Upvotes: 2

Related Questions