I don't understand the reason for doing Model.limit(6).offset(5) when we have to get 6 elements starting from the 6th index. I think that it should be Model.offset(5).limit(6) since we first have to tell the index from which we have to start retrieving the elements and then limit the search to the number of elements passed as argument to limit, and not the other way round.
3 Answers
The thing is you mistakenly suppose that the order of chained rails methods matters. In fact, it does not. Unless the real execution method is called, all these methods just change the internal query that is being prepared:
> User.limit(6).class #⇒ User::FriendlyIdActiveRecordRelation > User.offset(5).class #⇒ User::FriendlyIdActiveRecordRelation That said, the order just does not matter, unless one calls the execution method, like each (directly or via methods like to_a, map, etc.) or pluck.
> User.limit(6).offset(5).to_sql #⇒ "SELECT `users`.* FROM `users` LIMIT 6 OFFSET 5" > User.offset(5).limit(6).to_sql #⇒ "SELECT `users`.* FROM `users` LIMIT 6 OFFSET 5" 6The two are equivalent. The SQL is generated by ActiveRecord when you evaluate and get the results from it. Use .to_sql to see the SQL that gets generated:
[1] pry(main)> User.offset(6).limit(5).to_sql => "SELECT `users`.* FROM `users` LIMIT 5 OFFSET 6" [2] pry(main)> User.limit(5).offset(6).to_sql => "SELECT `users`.* FROM `users` LIMIT 5 OFFSET 6" The sql query generated by both cases mentioned in your question is same and hence they produce same results. So basically there is no difference in the order of using offset and limit for the same model.
>> Model.offset(5).limit(6).pluck(:id) # SELECT `model`.`id` FROM `model` LIMIT 6 OFFSET 5 # [6, 7, 8, 9, 10, 11] >> Model.limit(6).offset(5).pluck(:id) # SELECT `model`.`id` FROM `model` LIMIT 6 OFFSET 5 # [6, 7, 8, 9, 10, 11]