Bharat Bharat - 26 days ago 22
SQL Question

ActiveRecord Join Query and select in Rails

In my rails 4 application, a client (clients table) can have many projects (projects table). I have a column called 'name' in each table. I am trying to write a join and then select which uses projects as the base table and clients as the lookup table. client_id is the foreign_key in the projects table:

I am writing my query as follows:

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

I get the following response:

Project Load (0.6ms) SELECT projects.id,projects.name,clients.name FROM "projects" INNER JOIN "clients" ON "clients"."id" = "projects"."client_id"
=> #<ActiveRecord::Relation [#<Project id: 1, name: "Fantastico Client">]>


If I try to alias it like so:

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

Then I get the following response:

Project Load (0.8ms) SELECT projects.id,projects.name,clients.name as client_name FROM "projects" INNER JOIN "clients" ON "clients"."id" = "projects"."client_id"
=> #<ActiveRecord::Relation [#<Project id: 1, name: "The Dream Project">]>


In either case, ActiveRecord looses one of the names as you can see from the above response. How should I be writing this query?

vee vee
Answer

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
Comments