轨道3 - 选择具有包括哪些内容? [英] Rails 3 - select with Include?
问题描述
下面是一个嵌套的选择与包括:
Here is a nested select with include:
@items = Item.where("complete = ?", true).includes( :manufacturer, {:order=>[:supplier, :agent] })
这是一个繁重的查询,因为它拉的数据行从1000以上所有列入表中。
This is a taxing query as it pulls 1000s of rows of data from all the above included tables.
我怎样才能查询,只选择特定的领域?
How can I get the query to only select specific fields?
- user.name,user.created_at
- order.created_at
- supplier.name
- agent.name
- manufacturer.name
推荐答案
有一个在阿雷尔一个选择方法,但是你必须使用正确的表名(即复数,要注意,如果你有多态性模式,或者如果你使用set_table_name或一些其他类似的不规范做法)
There is a select method in ARel, but you must use the correct table names (i.e. plural and beware if you have polymorphic models or if you're using set_table_name or some other similar non-standard practice)
@items = Item.
select('users.name', 'users.created_at', 'orders.created_at', 'suppliers.name', 'agents.name', 'manufacturers.name').
where(:users => { :fulfilled => true }).
includes(:orders => [:supplier, :agent], :manufacturer)
我们可以使用选择与联接不包含 - @Bhavesh_A_P
"We can use select with joins not includes" - @Bhavesh_A_P
由于@Bhavesh_A_P上文所指出的,选择
与包括
不产生一致的行为。看来,如果所包含的关联不返回任何结果,选择
将正常工作,如果返回的结果,select语句将没有任何效果。实际上,它会被完全忽略,例如,你的选择语句可能会参照无效的表名和将不产生误差。 选择
与加入
将产生一致的行为。
As @Bhavesh_A_P pointed out above, select
with includes
does not produce consistent behavior. It appears that if the included association returns no results, select
will work properly, if it returns results, the select statement will have no effect. In fact, it will be completely ignored, such that your select statement could reference invalid table names and no error would be produced. select
with joins
will produce consistent behavior.
这篇关于轨道3 - 选择具有包括哪些内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!