在我的Rails 4应用程序中,一个客户端(clients表)可以有许多项目(projects表)。我在每个表中都有一个名为 name 的列。我试图写一个 join 然后 select ,它使用项目作为基础表,客户端作为查找表。 client_id 是projects表中的 foreign_key :
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')我得到以下响应:
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')然后我得到以下响应:
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">]>在上述两种情况下,ActiveRecord都会丢失其中一个名称,如您在上述响应中所见。我应该如何编写此查询?
In either case, ActiveRecord looses one of the names as you can see from the above response. How should I be writing this query?
推荐答案如果中的列选择不是在其上调用 select 的模型的属性之一,因此不会显示这些列。所有这些属性仍然包含在 AR :: Relation 内的对象中,并且可以像其他任何公共实例属性一样访问。
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.
您可以通过调用 first.client_name 进行验证:
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更多推荐
ActiveRecord联接查询并在Rails中选择
发布评论