ActiveRecord联接查询并在Rails中选择

编程入门 行业动态 更新时间:2024-10-27 17:24:44
本文介绍了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中选择

本文发布于:2023-10-22 08:08:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1516943.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:并在   ActiveRecord   Rails

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!