Rails: correct way of turning activerecord relation to array?
If you need to access to the query result, just use #to_a
on ActiveRecord::Relation instance.
At rails guides you can find on notable changes at Rails 4.0: "Model.all now returns an ActiveRecord::Relation, rather than an array of records. Use Relation#to_a if you really want an array. In some specific cases, this may cause breakage when upgrading." That is valid for other relation methods like :where.
selected_videos = videos.to_a.uniq{|p| p.author}
.uniq
does not make much sense when it is applied across the full active-record record.
Given that at least one or more of the three attributes - id
, created_at
, and updated_at
- are different for every row, applying videos.uniq{|p| p.author}
where videos
is a ActiveRecord::Relation
including all fields, will return all the rows in the ActiveRecord::Relation
.
When the ActiveRecord::Relation
object has a subset of values, uniq
will be able to figure out the distinct values from them.
Eg: videos.select(:author).uniq.count
will give 10 in your example.
The difference between ActiveRecord::Relation#uniq
and Array#uniq
is that the Array version accepts a block and uses the return value of a block for comparison. The ActiveRecord::Relation version of uniq simply ignores the block.