Search code examples
ruby-on-railsruby-on-rails-4active-record-query

Rails 4: Limit field selection through association


I know you can limit the returned fields in a Rails query by doing:

c = Client.select(:id, :user_id, :location_id).where(name: "John Doe")
=> #<ActiveRecord::Relation [#<Client id: 349, user_id: 348, location_id: 2>]>

but if you can only access the model through an association, how can you accomplish the same? (in this example Client belongs_to :user)

User.find_by(email: "[email protected]").client # I only want the 3 fields above

Solution

  • You can do it for example using scope, instead of association method:

    Client.select(:id, :user_id, :location_id)
          .find_by(user_id: User.find_by(email: '[email protected]').id)
    

    or even better, joining user and querying directly over users.email column:

    Client.select(:id, :user_id, :location_id)
          .joins(:user).find_by(users: { email: '[email protected]' })