# # #

Rails 4: Limit field selection through association

246 Views Asked by At

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
1

There are 1 best solutions below

0
Marek Lipka On BEST ANSWER

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]' })