Reputation: 610
I recently stumbled upon this blog post, which states that Array#uniq behaves differently on arrays of ActiveRecord objects, but neither gives a specific example for it, nor does it tell the reason for this.
I would like to see a reproducible example of this the different behavior and an explanation for it.
edit: I'm talking about Array#uniq, not ActiveRecord::Relation#uniq. If the latter one is what the above mentioned blog post actually means, then my question has been already been answered by loz (see below).
Upvotes: 1
Views: 492
Reputation: 117
Active record 'arrays' are not arrays they are a different. So (asside from .all, which explicitly returns an array) if you use associations or similar you get different behavior, as lazy loading is in operation:
post = Post.find(1)
post.comments
=> Array[Comment(:1), Comment(:2)]... etc
Looks like an array, but
post.comments.class
=> ActiveRecord::Relation
So performing Uniq operates on the relationship, which adds more constraints to the query which will eventually be run on the database when the records are required:
post.comments.uniq
This will perform the uniq by doing a DISTINCT or UNIQUE query clause in SQL, rather than doing uniq in ruby..
Uniq details are found here: rails uniq documentation, and you can see about what returns ActiveRecord::Relation in active record here
Upvotes: 1