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

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

问题描述

有人可以简要地向我解释 uniq distinct 方法之间的区别吗?

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#活动记录弃用

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

提示

使用 .includes ,然后调用 .uniq / .distinct 可以慢速加速您的应用,因为

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


  • uniq 不会产生其他sql查询

  • 与众不同

  • uniq won't spawn additional sql query
  • distinct will do

但是两个结果将相同

示例:

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 .count

  • 存在吗? .exists?

  • pluck map

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

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

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