David Geismar
David Geismar

Reputation: 3422

Rails Active Record : How do you preload multi level association with an extra dynamic criteria

In the models :

  Organization has_many Users
    Users has_many Registrations
    Registration belongs_to Organization

In my view organization#show, I am going to have something like

organization.users.each do |user|
 user.registrations.where(organization_id: organization.id).each do |registration|
   # display a registration
 end
end

In the controller to avoid N + 1 query on registrations, I could do something like:

@organization = Organization.includes(users: :registrations)find(params[:id])

However this won't work because I actually have an extra criteria on registration where(organization_id: organization.id).

How can I preload all registrations that belong to a user within the organization and that belong to the said organization to avoid N + 1 query here.

Upvotes: 1

Views: 698

Answers (1)

Sebastián Palma
Sebastián Palma

Reputation: 33420

Considering that a user belongs to an organization, there should be an organization_id in the users table, and the models must be related to each other. Perhaps you can try joining Registration with User and filtering by the users.organization_id column;

Registration.joins(:user).where(users: { organization_id: 1 })

Upvotes: 1

Related Questions