Rails:uniq vs. distinct
有人可以简单地向我解释uniq
和distinct
方法之间的distinct
吗?
我已经看到两者都在类似的背景下使用,但差异对我来说并不十分清楚。
-
.distinct
方法用于sql查询 -
.uniq
方法用于数组
rails查询也是一个数组,因此.uniq
产生与.distinct
相同的结果
注意:在Rails 5+中,不推荐使用Relation#distinct
Relation#uniq
,建议使用Relation#distinct
。 见http://edgeguides.rubyonrails.org/5_0_release_notes.html#active-record-deprecations
从文档 :
uniq(value = true)
ActiveRecord::QueryMethods#distinct
别名ActiveRecord::QueryMethods#distinct
它不完全回答你的问题,但我所知道的是:
如果我们考虑ActiveRecord上下文,那么uniq只是distinct的别名。 并且两者都可以在查询结果集上删除重复项(最多可以说是一个级别)。
在数组上下文中,uniq非常强大,即使元素是嵌套的,它也会删除重复项。 例如
arr = [["first"], ["second"], ["first"]]
如果我们这样做
arr.uniq
答案是: [["first"], ["second"]]
因此,即使元素是块,它也会深入并消除重复。
希望它在某些方面对你有所帮助。
- 我需要帮助正确形成这个ActiveRecord关联
- Rails应用程序错误 – ActiveRecord :: PendingMigrationError正在等待迁移; 运行’rake db:migrate RAILS_ENV = development’来解决此问题
- 如何塑造“特色”的概念(即,当一位艺术家在歌曲中“精选”时)
- Rails仅迭代与对象关联的持久记录
- Ruby委托类/关系级方法
- 使用ActiveRecord和Rails将数据插入postgresql数据库会出现此错误:RuntimeError:ERROR C22003 Minteger o
- ActiveRecord序列化将nil发送到当前属性的自定义序列化程序
- 显示消息数组中的最后一条消息
- Unicorn和Rails占用了2倍的MySQL连接