Rails 中的 pluck 和 collect 有什么区别? [英] What is the difference between pluck and collect in Rails?

查看:59
本文介绍了Rails 中的 pluck 和 collect 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有两个示例代码.

第一个带有 collect 的:

User.first.gifts.collect(&:id)

带有 pluck 的第二个:

User.first.gifts.pluck(:id)

它们在性能或其他方面有什么区别吗?

Is there any difference between them in performance or something else?

推荐答案

pluck 在 db 级别.它只会查询特定的字段.看到这个.

pluck is on the db level. It will only query the particular field. See this.

当你这样做时:

 User.first.gifts.collect(&:id)

由于基于 Enumerable 的方法,您拥有加载了所有字段的对象,并且您只需获得 id.

You have objects with all fields loaded and you simply get the id thanks to the method based on Enumerable.

所以:

  • 如果您需要 Rails 4 的 id,请使用 ids:User.first.gifts.ids

  • if you only need the id with Rails 4, use ids: User.first.gifts.ids

如果您需要 Rails 4 的某些字段,请使用 pluck:User.first.gifts.pluck(:id, :name,...)

if you only need some fields with Rails 4, use pluck: User.first.gifts.pluck(:id, :name, ...)

如果您需要 Rails 3 的一个字段,请使用 pluck:User.first.gifts.pluck(:id)

if you only need one field with Rails 3, use pluck: User.first.gifts.pluck(:id)

如果您需要所有字段,请使用collect

if you need all fields, use collect

如果你需要一些 Rails 4 的字段,仍然使用 pluck

if you need some fields with Rails 4, still use pluck

如果你需要一些 Rails 3 的字段,使用 selectcollect

if you need some fields with Rails 3, use selectand collect

这篇关于Rails 中的 pluck 和 collect 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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