导轨选择,包括 [英] rails select and include

查看:109
本文介绍了导轨选择,包括的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能解释一下吗?

Project.includes([:user, :company])

这3执行查询,一来获取项目,一个获取用户为这些项目和一个获取公司。

This executes 3 queries, one to fetch projects, one to fetch users for those projects and one to fetch companies.

Project.select("name").includes([:user, :company])

这3执行查询,并完全忽略选择位。

This executes 3 queries, and completely ignores the select bit.

Project.select("user.name").includes([:user, :company])

这执行1查询适当的左连接。而且还是完全忽视了选择。

This executes 1 query with proper left joins. And still completely ignores the select.

这似乎对我来说,轨道忽略使用包括选择。那么好吧,但为什么当我把相关的模型,选择它从发行3查询发1查询转换?

It would seem to me that rails ignores select with includes. Ok fine, but why when I put a related model in select does it switch from issuing 3 queries to issuing 1 query?

注意1查询是我想要的,我不能想象这是正确的方式来得到它也没有说明为什么它的工作原理,但我不知道怎么回事,得到的结果在一个查询(.joins似乎只能使用INNER JOIN,我不​​其实想,当我手动specifcy联接条件.joins我们使用怪胎出来的搜索宝石,因为它试图重新添加具有相同名称的连接)。

Note that the 1 query is what I want, I just can't imagine this is the right way to get it nor why it works, but I'm not sure how else to get the results in one query (.joins seems to only use INNER JOIN which I do not in fact want, and when I manually specifcy the join conditions to .joins the search gem we're using freaks out as it tries to re-add joins with the same name).

推荐答案

还好吧所以这里就是我想出了...

Allright so here's what I came up with...

.joins("LEFT JOIN companies companies2 ON companies2.id = projects.company_id LEFT JOIN project_types project_types2 ON project_types2.id = projects.project_type_id LEFT JOIN users users2 ON users2.id = projects.user_id") \
.select("six, fields, I, want")

作品,讨人厌,但它让我正是我需要在一个查询中的数据。唯一糟糕的部分是我必须付出一切一个模型2的别名,因为我们使用的是meta_search,这似乎无法找出一个表时,可以指定自己的连接条件已经加入。

Works, pain in the butt but it gets me just the data I need in one query. The only lousy part is I have to give everything a model2 alias since we're using meta_search, which seems to not be able to figure out that a table is already joined when you specify your own join conditions.

这篇关于导轨选择,包括的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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