0
0
Ruby on Railsframework~30 mins

Scopes for reusable queries in Ruby on Rails - Mini Project: Build & Apply

Choose your learning style9 modes available
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 attributes
Add a scope called published that returns only posts where published is true
Add a scope called recent that returns posts created within the last 7 days
Use 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
1
Create the Post model with attributes
Create a Post model class that inherits from ApplicationRecord with attributes title, body, published, and created_at.
Ruby on Rails
Need a hint?

Define the model class and mention the attributes as comments for clarity.

2
Add a scope for published posts
Add a scope called published in the Post model that returns posts where published is true using where(published: true).
Ruby on Rails
Need a hint?

Use scope :published, -> { where(published: true) } to define the scope.

3
Add a scope for recent posts
Add a scope called recent in the Post model that returns posts created within the last 7 days using where('created_at >= ?', 7.days.ago).
Ruby on Rails
Need a hint?

Use scope :recent, -> { where('created_at >= ?', 7.days.ago) } to define the recent posts scope.

4
Use the scopes in a query
Write a query using the Post model that chains the published and recent scopes to get posts that are published and created within the last 7 days.
Ruby on Rails
Need a hint?

Chain the scopes by calling Post.published.recent and assign it to posts.