We build Web & Mobile Applications.

< All Articles

Giving ActiveRecord finders an :offset but not a :limit

Sometimes you might want to find all records from a specific offset but ActiveRecord won’t let you: if you use the :offset option without specifying a :limit you won’t get an error, Rails will just silently discard the offset.

You could get around this by passing :limit => MyModel.count option to the finder but this adds the unnecessary overhead of an additional query. Instead I prefer to pass a value that is more than the largest possible value for the primary key, like this:

MyModel.all :offset => 100, :limit => 2**32, :order => :name

In this example MyModel has a regular integer sized primary key so 2**32 is larger than the maximum number of records that can be stored in the table, so we’re guaranteed to get all the records from offset 100 onwards.

Updated on 16 July 2015
First published by Chris Anderton on 07 April 2009
© TheWebFellas Limited 2016
"Giving ActiveRecord finders an :offset but not a :limit" by Chris Anderton at TheWebFellas is licensed under a Creative Commons Attribution 4.0 International License.