1

So in the same way that you could do @items.active.first to get the first item, is there a way to select something else, like 56th?

Obviously @items.active.fiftysixth doesn't work, but is there some other method for accessing that?

1 Answer 1

4

When the collection is a relation, you can use offset (.first just translates to limit 1 in SQL)

@items.active.offset(55).first 

Or, if it's an array:

@items.active[55] 
Sign up to request clarification or add additional context in comments.

7 Comments

The 56th element is index 55. Ruby arrays start at 0.
@items.active.offset(55).first. While @items.active[55] is very bad idea
@fl00r it depends. If he only ever wants the 56th entry, then offset is preferred, if he wants many entries, or to traverse the collection based on some calculation he's probably better fetching the whole collection and indexing it as an array.
As an aside, do you think rails guarantees row order in a given table?
@PerryHorwich I believe Rails simply puts them in whatever order the database returns them. If you specify an .order, then they'll be in that order. Otherwise, there are no guarantees.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.