Rails:uniq 与不同 [英] Rails: uniq vs. distinct

查看:30
本文介绍了Rails:uniq 与不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能给我简单解释一下uniqdistinct方法在使用上的区别?

Can someone briefly explain to me the difference in use between the methods uniq and distinct?

我见过两者都用在相似的上下文中,但我不太清楚区别.

I've seen both used in similar context, but the difference isnt quite clear to me.

推荐答案

Rails 查询就像数组,因此 .uniq 产生与 .distinct 相同的结果,但是

Rails queries acts like arrays, thus .uniq produces the same result as .distinct, but

  • .distinct 是sql查询方法
  • .uniq 是数组方法
  • .distinct is sql query method
  • .uniq is array method

注意:在 Rails 5+ 中,Relation#uniq 已被弃用,建议改用 Relation#distinct.请参阅 http://edgeguides.rubyonrails.org/5_0_release_notes.html#active-record-弃用

Note: In Rails 5+ Relation#uniq is deprecated and recommended to use Relation#distinct instead. See http://edgeguides.rubyonrails.org/5_0_release_notes.html#active-record-deprecations

提示:

在调用 .uniq/.distinct 之前使用 .includes 可以减慢加速您的应用程序,因为

Using .includes before calling .uniq/.distinct can slow or speed up your app, because

  • uniq 不会产生额外的 sql 查询
  • distinct 会做
  • uniq won't spawn additional sql query
  • distinct will do

但是两个结果都是一样的

But both results will be the same

示例:

users = User.includes(:posts)
puts users
# First sql query for includes

users.uniq
# No sql query! (here you speed up you app)
users.distinct
# Second distinct sql query! (here you slow down your app)

这对制作高性能应用程序很有用

This can be useful to make performant application

提示:

同样适用

  • .size vs .count;
  • present? vs .exists?
  • map vs pluck
  • .size vs .count;
  • present? vs .exists?
  • map vs pluck

这篇关于Rails:uniq 与不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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