Rails: correct way of turning activerecord relation to array?
.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.
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}
If you need the records, you can use ActiveRecord::Relation#load
Causes the records to be loaded from the database if they have not been loaded already. You can use this if for some reason you need to explicitly load some records before actually using them. The return value is the relation itself, not the records.
https://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-load