Back to Tutorials
Tips6/8/2025

Scopes in Rails 4

railsrails 4rubyscopes

Today we will see a quick tip about scopes in Rails 4.

You may have been used to this kind of scopes with Rails 3 :

 scope :active, where(active: true)

But in Rails 4, you need to give it a callable object like a Proc or a Lambda :

 scope :active, -> { where(active: true) }

You can also pass it a parameter :

 scope :things, -> (type) { where(type: type)}

You can still define class method if you prefer :

 self.active
      where(active: true)
 end

Whatever way you chose, always keep in mind that scopes have to be chainable. Therefore, they need to return an ActiveRecord::Relation object.

Comments

Loading comments...

Level Up Your Dev Skills & Income 💰💻

Learn how to sharpen your programming skills, monetize your expertise, and build a future-proof career — through freelancing, SaaS, digital products, or high-paying jobs.

Join 3,000+ developers learning how to earn more, improve their skills, and future-proof their careers.

Scopes in Rails 4 | Devmystify