ActiveRecord Join Query and select in Rails

If the column in select is not one of the attributes of the model on which the select is called on then those columns are not displayed. All of these attributes are still contained in the objects within AR::Relation and are accessible as any other public instance attributes.

You could verify this by calling first.client_name:

Project.joins(:client)
       .select('projects.id,projects.name,clients.name as client_name')
       .first.client_name

your query don't looses any thing. Actually you have applied join on models and you have written Project.joins(:client) that why it is looking like. means It will hold Project related data as it is and associated data hold with alias name that you have given 'client_name' in your query.

if you use

Project.joins(:client)
   .select('projects.id project_id, projects.name projects_name,clients.name as client_name')

then it look like [#, #]

but it hold all the attribute that you selected.


You can use :'clients.name' as one of your symbols. For instance:

Project.select(:id, :name, :'clients.name').joins(:client)

I like it better because it seems like Rails understands it, since it quotes all parameters:

SELECT "projects"."id", "projects"."name", "clients"."name"
FROM "projects"
INNER JOIN "clients" ON "clients"."id" = "projects"."client_id"

(I'm not 100% sure that's the exact SQL query, but I'm fairly certain and I promise it will use "clients"."name")