Search code examples
ruby-on-railsactiverecordeager-loading

Specifying Conditions on Multiple Nested Eager Loaded Associations


I'm trying to query on ActiveRecord multiple nested eager loaded associations with conditions like so:

user.books.includes(slot: [room: :school]).where("books.slot.room.school.id = 1")

Obviously this query is wrong, but basically what I'm trying to reach is a relation of user.books for a certain school.

My model structure is:

class User < ActiveRecord::Base
  has_many :books
  has_many :slots, through: :books
  has_many :rooms, through: :slots
  has_many :schools
end

class Book < ActiveRecord::Base
  belongs_to :user
  belongs_to :slot
end

class Slot < ActiveRecord::Base
  has_many :books
  belongs_to :room
end

class Room < ActiveRecord::Base
  belongs_to :school
  has_many :slots
end

class School < ActiveRecord::Base
  has_many :users
  has_many :rooms
  has_many :slots, through: :rooms
  has_many :books, through: :slots
end

Any ideas? Thanks in advance.


Solution

  • includes eager loads association records, while joins does what you want to do.

    This question has been asked here numerous times. Please make sure that you look and try to find a similar question here before you ask one.

    So you want to change your code like this:

    user.books.joins(slot: [room: :school]).where(schools: { id: 1 })