Rails uniq_by - Unique Results From ActiveRecord Relations
![](/assets/profile-db929485a25f624de9a5b0421c00c1a2da123707bd8bea006446c92b26231ea3.png)
I just discovered a neat method in rails called uniq_by
. ( http://apidock.com/rails/Array/uniq_by )
It allows you to get a unique set of results from an active record relation.
Ruby provides a way to get unique results from an array like so:
a = [1, 2, 3, 3, 4]
a.uniq # results [1, 2, 3, 4]
But if you have an active record relation, the normal uniq
won't work.
Say you have a list of stores and you want to find their location, but
you only want 1 location from each store/company. You can use:
Location.near("monroe, ga").uniq_by(&:store_id)
And that will give you a nice unique Array from an AR relation!