我知道我可以用pluck
指定某些字段来查询数据库。在Rails和ActiveRecord中查询时忽略某个字段
ids = Item.where('due_at < ?', 2.days.from_now).pluck(:id)
但是,我想知道,是否有一种方法来指定某些字段,我想避免从数据库查询。某种反采摘?
posts = Post.where(published: true).do_not_lookup(:enormous_field)
我知道我可以用pluck
指定某些字段来查询数据库。在Rails和ActiveRecord中查询时忽略某个字段
ids = Item.where('due_at < ?', 2.days.from_now).pluck(:id)
但是,我想知道,是否有一种方法来指定某些字段,我想避免从数据库查询。某种反采摘?
posts = Post.where(published: true).do_not_lookup(:enormous_field)
Model#attribute_names
应该返回数组的列/属性。您可以排除其中一些并传递给pluck
或select
方法。
像这样:
posts = Post.where(published: true).select(Post.attribute_names - ['enormous_field'])
pluck比select要快得多 - http://guides.rubyonrails.org/active_record_querying.html#pluck – Anthony 2015-03-03 13:31:01
不是, 'pluck'在引擎盖下使用'select',它只是将结果作为一个数组返回,而将'select'作为记录。 – tompave 2015-03-03 13:37:15
@tompave这个家伙不同意。超过90%的采摘速度更快:http://gavinmiller.io/2013/getting-to-know-pluck-and-select/ – 2015-03-03 13:38:32
Item.where( 'due_at <?',2.days.from_now).MAP {| A | a.attributes.except!(“email”,“id”)。values} – user3118220 2015-03-03 13:59:32
参见我的回答 – user3118220 2015-03-03 13:59:44