0
0
Ruby on Railsframework~5 mins

Order and limit in Ruby on Rails

Choose your learning style9 modes available
Introduction

Ordering and limiting help you get data sorted and control how many results you see. This makes it easier to find what you want quickly.

Showing the newest posts first on a blog.
Displaying the top 5 highest scores in a game.
Listing users alphabetically in a directory.
Getting the latest 10 comments on an article.
Syntax
Ruby on Rails
Model.order(column_name: :direction).limit(number)

order sorts the results by a column, either ascending (:asc) or descending (:desc).

limit restricts how many records you get back.

Examples
Get the 5 newest users by creation date.
Ruby on Rails
User.order(created_at: :desc).limit(5)
Get 10 products sorted alphabetically by name.
Ruby on Rails
Product.order(name: :asc).limit(10)
Get all articles sorted by most recently updated first.
Ruby on Rails
Article.order(updated_at: :desc)
Get any 3 comments without sorting.
Ruby on Rails
Comment.limit(3)
Sample Program

This code fetches the 3 latest posts sorted by their published date in descending order. Then it prints each post's title and date.

Ruby on Rails
class Post < ApplicationRecord
end

# Get the 3 most recent posts
recent_posts = Post.order(published_at: :desc).limit(3)

recent_posts.each do |post|
  puts "#{post.title} - Published on #{post.published_at.strftime('%Y-%m-%d')}"
end
OutputSuccess
Important Notes

You can chain order and limit together for precise queries.

If you don't use order, limit will return any records, but the order is not guaranteed.

Use symbols for column names and directions for clarity and safety.

Summary

Order sorts your data by a column.

Limit controls how many records you get.

Use them together to get sorted, smaller sets of data easily.