Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
812 views
in Technique[技术] by (71.8m points)

activerecord - Rails: uniq vs. 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.

question from:https://stackoverflow.com/questions/39575398/rails-uniq-vs-distinct

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

  • .distinct is sql query method
  • .uniq is array method

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

Hint:

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

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

But both results will be the same

Example:

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

Hint:

Same works for

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...