Ruby on Rails

Rails default sorting

The default_scope method in a model lets us sort records in a default sorting order, like so:

class Post < ApplicationRecord

  default_scope order(created_at: :desc)
end

default_scope is used to set any default on operations on a model. Here’s another example:

default_scope where(deleted_on: nil)

Even though default_scope is useful in certain circumstances, it has its drawbacks, and it’s probably better to avoid using it in favor of setting explicit scopes instead.

Here’s an example:

class PostsController < ApplicationController
  def index
    @posts = Post.order(created_at: :desc)
  end
end

Here’s an article on Why using default_scope is a bad idea

← All posts Recent blog posts →