新手问题 看文档很多查询都是默认查询所有字段,有没有只查询一个字段或部分字段的

lfz · April 26, 2016 · Last by qinfanpeng replied at April 29, 2016 · 1882 hits

看文档很多查询都是默认查询所有字段,有没有只查询一个字段或部分字段的,而且有条件的(就是要用到 where xx=xx 的)

Model.select(:column).where(xx: xx)

Model.pluck(:id)

select 用来筛选出返回的字段,最后得到的仍然是对象。 pluck 用来直接返回某个字段本身的值。比如 pluck(:id) 就返回一个整数数组。

pluck 省去了 active record 对象的 construction,更快。

场景是什么,没有特殊场景不必要更改默认行为。

这里得分两种情况:

  1. 查询出的数据量较大,为了减少内存空间占用,那请用 1 楼的方法 ruby Model.select(:field, :other_field, :and_one_more) # => [#<Model id: nil, field: "value", other_field: "value", and_one_more: "value">]
  2. 只希望获取特定列值的集合,而非对象集合,那么 ruby Model.pluck(:field, :other_field, :and_one_more)

#6 楼 @qinfanpeng 如果是 rails3 pluck 不能获取多列吧,需要重新定义 pluck 方法。。。

#7 楼 @yaocanwei 这个倒记不清了,不过看下文档就知道了。

You need to Sign in before reply, if you don't have an account, please Sign up first.