3

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) }

2 Answers 2

8

If you mean indexes in an array (not IDs):

collection.values_at(3, 5, 9, 11)
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks tokland, This does work! I'm trying to update attributes on a collection for testing. is this the best way to get at it?
Actually, I believe I can't update attributes on an array. I think I need to do an each. I'll keep working at it. Thanks again tokland!
Thanks tokland. I got it working, and provided the code in my edit above... (hopefully that was the right place to do so)
1

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.

2 Comments

Thanks WarHog, but I'm trying to avoid using ID's as this is for a test db, and they will be constantly changing...
Aha, got it, sorry for my misunderstanding.. Then @tokland approach should help you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.