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?
Solution 1:
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
Solution 2:
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"
)
Solution 3:
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.
Solution 4:
To get both project table name and client name you can do like below query
Project.joins(:client).pluck(:name,:'clients.name')