Scopes for reusable queries
📖 Scenario: You are building a simple blog application where you want to easily find published posts and posts created recently.
🎯 Goal: Create reusable query scopes in the Post model to filter published posts and recent posts.
📋 What You'll Learn
Create a
Post model with title, body, published (boolean), and created_at attributesAdd a scope called
published that returns only posts where published is trueAdd a scope called
recent that returns posts created within the last 7 daysUse ActiveRecord query methods to define the scopes
💡 Why This Matters
🌍 Real World
Scopes help keep your Rails code clean and DRY by reusing common queries across your app.
💼 Career
Understanding scopes is essential for Rails developers to write maintainable and efficient database queries.
Progress0 / 4 steps