ruby-on-railsactiverecordrails-postgresql

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


Solution

  • 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