Remon Amin
Remon Amin

Reputation: 1548

rails select with includes

I have these code in my rails 3.2 application

User.includes(:profile).limit(10)

which select all fields from profiles table I need a way to select on specific fields from profiles table to decrease db queries I am using postgresql

Upvotes: 4

Views: 19547

Answers (3)

bkunzi01
bkunzi01

Reputation: 4561

Rails 5 Way: Just add a reference to the associated table name.

User.includes(:profile).select("users.*, profiles.field1, profiles.field2").limit(10).references(:profiles)

Upvotes: 2

Astery
Astery

Reputation: 1256

I think you, ask for select method.

User.includes(:profile).limit(10).select(:field1, :field2)

Update:

The answer from @Hassan woudn't really work. Look here (Eager loading section)

Since only one table is loaded at a time, conditions or orders cannot reference tables other than the main one.

Try following:

class User < ActiveRecord::Base
  has_one :profile_w_name, -> { select(:id, :name, :user_id).limit(10) }, class_name: 'Profile'
end

User.includes(:profile_w_name).first.profile_w_name

Don't forget to add user_id field, because AR will try to preload profile field.

Update:

I found a better solution for all above, after I saw deprecation warning that complains about eager loading and SQL snippet for references like select("post.id, comment.post_id"). Rails 4 required.

User.includes(:profile).select(:field1, :field2).references(:profile)

Also checkout this gist to see difference https://gist.github.com/astery/6137727

Upvotes: 8

Hassan Javeed
Hassan Javeed

Reputation: 464

You're better of using something like

User.joins(:profile).select("users.*, profiles.field1, profiles.field2").limit(10)

Upvotes: 9

Related Questions