Reputation: 4074
I'm trying to select a collection of objects using ActiveRecord by the index in the array.
I know I can select Item.first or Item.last or single or range. But I want to update an arbitrary group by the index of their position in the array.
collection = Item.all.to_a
collection[3,5,9,11]
Is this possible?
Thanks in advance...
-- edit --
Thanks to tokland's help, I was able to get it to work perfect.
In case anyone else wants to do something similar, here is what I did:
yesterday = Time.now - 1.day
i = Item.all
new_items = i.values_at(1,3,5,10,11,14,18)
new_items.each{ |e| e.update_attributes(:published_at => yesterday) }
Upvotes: 3
Views: 4488
Reputation: 8710
If i properly understand, you need
Item.find([3,5,9,11])
This is how you can find a record given an id. But it method throws an exception if there would be some id that doesn't exist.
Item.find_all_by_id([3,5,9,11])
That will work even if some of the ids don't exist.
Upvotes: 1
Reputation: 67850
If you mean indexes in an array (not IDs):
collection.values_at(3, 5, 9, 11)
Upvotes: 8