4

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

Chris Travers
  • 25,424
  • 6
  • 65
  • 182
Remon Amin
  • 1,506
  • 2
  • 19
  • 44

3 Answers3

9

You're better of using something like

User.joins(:profile).select("users.*, profiles.field1, profiles.field2").limit(10)
Hassan Javeed
  • 464
  • 4
  • 14
7

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

Astery
  • 1,216
  • 13
  • 22
  • It will select from users table I want to select specific fields from profiles table – Remon Amin Aug 02 '13 at 03:07
  • Why do you think so? Did you try the gist? – Astery Dec 18 '15 at 10:43
  • if I understand correct the 2nd update, you can do something like this? `@users = User.includes(:profile).select('user.id, user.name, profile.id, profile.something, profile.something_else').references(:profile)` ? – ltdev Oct 14 '16 at 10:41
  • So this would generate two queries like these? `SELECT id, name FROM users` and `SELECT id, something, something else FROM profiles WHERE user_id IN ( user IDs here )` – ltdev Oct 14 '16 at 10:44
  • @Lykos, I left a comment with debug output for you in gist. – Astery Oct 15 '16 at 16:17
2

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)
bkunzi01
  • 4,504
  • 1
  • 18
  • 25
  • 1
    Try now. I had left out the "." operator on the call to limit(10). Now fixed. – bkunzi01 Nov 22 '19 at 16:29
  • 1
    Still, it doesn't work. You can check this answer https://stackoverflow.com/questions/12400860/activerecord-includes-specify-included-columns – Aniket Tiwari Nov 23 '19 at 04:30