Toby
Toby

Reputation: 8792

Removing redundant queries using Active Record

The following code works, but runs far too many SQL statements for my liking;

User.includes([:profile,:roles]).select("id, email, created_at, confirmed_at, countries.name").find_in_batches do |users| 
        users.map{|u| # In here I access profile.country.name} 
end

What is meant to do is grab the User information along with some profile information and put it into a csv format.

Inside the .map I am calling profile.country.name this is coming in fine but Rails is running an extra SQL call to find the name, what I want to do is capture this information in my initial lookup.

My issue is that because country is linked to profile and not user I can't add it to my .includes because it doesn't see it as a linkable table. Is there anything I can do to force the includes to join a table linked to profile?

The relevant model information is below;

User:

has_one  :profile, dependent: :destroy

Profile:

belongs_to :user
belongs_to :country

Country:

has_many :profiles

Upvotes: 1

Views: 163

Answers (1)

brrygrdn
brrygrdn

Reputation: 36

You should be able to include country in the original query by nesting it under profile in the .includes call:

User.includes( {:profile => [:country], :roles} )

Upvotes: 2

Related Questions