TIL Rails enum attributes define scopes

Oliver Peate posted on December 27th, 2018

If you have an ActiveRecord enum:

class Post < ApplicationRecord
  enum status: {
    draft: "draft",
    published: "published",
  }
end

Then you get scopes for free:

Post.published
Post.draft

Here’s the implementation in ActiveRecord::Enum:

if enum_scopes != false
  klass.send(:detect_enum_conflict!, name, value_method_name, true)
  klass.scope value_method_name, -> { where(attr => value) }
end

What did you learn today?

Write a quick TIL post to reflect on what you've learned.

Write a post