Rails 3 - 选择包含? [英] Rails 3 - select with Include?

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

问题描述

这是一个包含包含的嵌套选择:

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
  • 供应商名称
  • 代理名称
  • 制造商名称

推荐答案

ARel 中有一个 select 方法,但是你必须使用正确的表名(即复数,如果你有多态模型或者你正在使用 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)

我们可以在不包含的情况下使用 select 和 joins" - @Bhavesh_A_P

"We can use select with joins not includes" - @Bhavesh_A_P

正如@Bhavesh_A_P 上面指出的那样,带有 includesselect 不会产生一致的行为.看起来如果包含的关联没有返回结果,select 会正常工作,如果它返回结果,select 语句将不起作用.事实上,它会被完全忽略,这样你的 select 语句可能会引用无效的表名,并且不会产生错误.selectjoins 将产生一致的行为.

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.

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

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