Bharat Bharat - 1 year ago 106
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:


I get the following response:

Project Load (0.6ms) SELECT,, 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(',, as client_name')

Then I get the following response:

Project Load (0.8ms) SELECT,, 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 Source

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:

       .select(',, as client_name')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download