sql - ActiveRecord Join Query and select in Rails -
in rails 4 application, client (clients table) can have many projects (projects table). have column called name in each table. trying write join , select uses projects base table , clients lookup table. client_id foreign_key in projects table:
i writing query follows:
project.joins(:client).select('projects.id,projects.name,clients.name') i following response:
project load (0.6ms) select projects.id,projects.name,clients.name "projects" inner join "clients" on "clients"."id" = "projects"."client_id" => #<activerecord::relation [#<project id: 1, name: "fantastico client">]> if try alias so:
project.joins(:client).select('projects.id,projects.name,clients.name client_name') then following response:
project load (0.8ms) select projects.id,projects.name,clients.name client_name "projects" inner join "clients" on "clients"."id" = "projects"."client_id" => #<activerecord::relation [#<project id: 1, name: "the dream project">]> in either case, activerecord looses 1 of names can see above response. how should writing query?
if column in select not 1 of attributes of model on select called on columns not displayed. of these attributes still contained in objects within ar::relation , accessible other public instance attributes.
you verify calling first.client_name:
project.joins(:client) .select('projects.id,projects.name,clients.name client_name') .first.client_name
Comments
Post a Comment