Haseeb Ahmad
Haseeb Ahmad

Reputation: 8730

Select associated attributes in join in rails

app/models/user.rb

has_one :user_detail

app/models/user_detail.rb belongs_to :user

When I query

User.active.
  select('users.id, users.first_name, users.last_name,user_details.unit_number').
  joins('LEFT JOIN user_details ON users.id = user_details.user_id').
  where(:property_id => params[:id])

It gives me only user model columns, not giving user_details.unit_number. How I get this?

I am doing this

users = User.active.select('users.id, users.first_name, users.last_name, user_details.unit_number').joins('LEFT JOIN user_details ON users.id = user_details.user_id').where(:property_id => params[:id])

users_list = users.as_json(:only => [:id, :first_name, :last_name, :unit_number)

Upvotes: 1

Views: 2730

Answers (2)

Meier
Meier

Reputation: 3880

By using select, you have stripped-down ActiveRecord objects, especially they have no longer the relation to your user_detail

You can make the user_detail attributs available in your user objects by using as in the select statement

User.active.
  select('users.id, users.first_name, users.last_name, user_details.unit_number as unit_number').
  joins('LEFT JOIN user_details ON users.id = user_details.user_id').
  where(:property_id => params[:id])

Then you should be able to access the information like it is a normal attribute of the user (and not of user_detail)

Upvotes: 2

Marek Lipka
Marek Lipka

Reputation: 51161

I would use built-in Rails tools for this (includes in this case):

users = User.active.includes(:user_detail).where(property_id: params[:id])

And now you can call, for example:

users.first.user_detail.unit_number

and you're guaranteed you don't have N + 1 problem

Upvotes: 0

Related Questions