Can a collection returned by active record be futher filtered using built-in methods?
I have a collection like this:
UserLevels
id
blah_id
blah2_id
..
..
Now I want to further file this collection with all rows that have
blah2_id = 3
I don't need to hit the database again as I already have this co开发者_StackOverflowllection, and this collection will have maybe 5-10 rows in it anyhow at most.
What's the best way to do this? Or what options do I have.
The first option that springs to mind is Array#select
(Ruby 1.9 only):
@collection = UserLevel.all
@filtered_collection = @collection.select { |l| l.blah2_id == 3 }
Ruby's Array
class is quite powerful, and is worth investigating: http://www.ruby-doc.org/core/classes/Array.html
In Ruby 1.8, the equivalent method is Enumerable#find_all
:
@filtered_collection = @collection.find_all { |l| l.blah2_id == 3 }
IMHO it would be better if you tweak your database query to fetch the desired objects. Using Array#select on large arrays is pretty slow.
Reasons - You entire array object will be loaded in memory. Array#select will then run the block on each element. Extremely memory intensive operation. You might not realize this on your development machine, but when you run this kind of operation on array with >5k records, you will feel the heat.
精彩评论