有人能简单地向我解释一下方法uniqdistinct在使用上的区别吗?

我见过这两个词在相似的语境中使用,但我不太清楚它们之间的区别.

推荐答案

Rails queries acts like arrays,因此.uniq产生与.distinct相同的结果,但是

  • .distinct是sql查询方法
  • .uniq是数组方法

Note:在Rails中,不推荐使用5+Relation#uniq,建议使用Relation#distinct.

Hint:

在拨打.uniq/.distinct之前使用.includes可以让你的应用程序达到slowspeed up,因为

  • uniq不会产生额外的sql查询
  • distinct美元就行了

但两种结果都是一样的

例子:

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)

这对于实现高性能应用程序非常有用

Hint:

同样适用于

  • .size.count
  • present?.exists?
  • mappluck

Ruby-on-rails相关问答推荐

`heroku Open`和`heroku run rake db:Migrate`不工作(";没有这样的文件或目录";)

我可以向 erb 变量插值添加一个类吗?

Rails:当 id 方法为非标准时构建关联

无法在生产服务器上启动 Rails 4 控制台

Ruby 地理定位Ruby /插件

rake assets:precompile try 连接到数据库

如何为 Rails SimpleForm Select 框设置默认 Select 值

Rails 中页面视图的简单计数器

为什么使用 HTTP PUT 和 DELETE 方法而不是 POST?

在 Nokogiri 中获取属性值以提取链接 URL

在 Rails 4 中检测用户代理 - 读取 HTTP 标头

不允许请求来源:使用 Rails5 和 ActionCable 时的 http://localhost:3001

在 ruby​​ 中构建公钥时,是什么导致既不是 PUB key 也不是 PRIV key::nested asn1 错误?

Ruby on Rails 中的MySQL 服务器已经消失

格式化日期对象以显示人类可读的日期

Rails 中是否有 HTML 安全截断方法?

在 Rails 路由中更改 id 参数

如何使用 url 连接到 postgresql

Ruby 更新后:测试失败,assets资源 未声明为在生产中预编译

如何拆分长行的 Ruby