ActiveRecord联接查询并在Rails中选择 [英] ActiveRecord Join Query and select in Rails

查看:71
本文介绍了ActiveRecord联接查询并在Rails中选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的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中选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆