在Rails和ActiveRecord中查询时忽略某个字段

The*_* Oz 5 ruby activerecord ruby-on-rails ruby-on-rails-4

我知道我可以指定某些字段来查询数据库pluck.

ids = Item.where('due_at < ?', 2.days.from_now).pluck(:id)
Run Code Online (Sandbox Code Playgroud)

但是我想知道,是否有一种方法可以指定某些字段,我希望避免从数据库中查询.某种反拔?

  posts = Post.where(published: true).do_not_lookup(:enormous_field)
Run Code Online (Sandbox Code Playgroud)

Max*_*kov 9

Model#attribute_names应该返回列/属性的数组.您可以排除其中一些并传递给pluckselect方法.

像这样的东西:

posts = Post.where(published: true).select(Post.attribute_names - ['enormous_field'])
Run Code Online (Sandbox Code Playgroud)

  • `pluck` 更快,因为它从数据库中提取特定列,然后停止并直接将它们作为数组返回。另一方面,“select”将执行 pluck 使用的_相同_查询,但将返回“ActiveRecord::Relation”。然后可以将该关系转换为完整记录的数组。缓慢的部分是转换为“ActiveRecord::Base” (2认同)