ActiveRecord querying: order/limit
This course covers how ActiveRecord sorts and restricts query results, using a six-row ScratchArticleQ table and real queries from this app. It explains why rows have no guaranteed order without .order, why ascending is the default and how :desc flips it, and how several columns break ties. It then covers .limit and .offset for pagination, the SQL behind .first(n) and .last(n), and how .reorder replaces an existing order. A final query object combines these methods to paginate a comment thread.
What you'll learn
- ✓Why query results have no guaranteed order without .order
- ✓Sorting ascending by default and descending with a hash like views: :desc
- ✓Ordering by several columns so later columns break ties
- ✓Paginating with .limit and .offset after an explicit order
- ✓How .first(n) and .last(n) build their SQL
- ✓Replacing an existing order with .reorder instead of appending
.order: ascending unless you say otherwise
ActiveRecord querying: where/find_by spent seven lessons on one question: which rows come back. .where and find_by narrow a table to the rows that match a condition, and that course ran every example on the scratch ScratchArticleQ table (title, category, published, views). This course asks a…
Read the full lesson free →Curriculum
7 lessons.order: ascending unless you say otherwise
Without .order rows have no guaranteed order, and .order(:column) sorts ascending by default.
.order(column: :desc): highest first
Passing a hash like views: :desc sorts highest first, the only way to get DESC in ActiveRecord.
Ordering by several columns at once
Several columns in one .order call sort by the first and break remaining ties with the rest.
.limit and .offset: restricting the result
.limit keeps the first n ordered rows and .offset skips rows, and together they implement pagination.
.first(n) and .last(n): shortcuts with a twist
.first(n) sends ORDER BY with LIMIT, and .last(n) flips the order, limits, then reverses the array.
.reorder: replacing instead of chaining
Calling .order twice appends columns, and .reorder discards the existing order and puts a new one in place.
Putting it together: a paginated, ordered query
A comment thread query combines ordering, offset and a per + 1 limit to detect a next page.