0
0
Ruby on Railsframework~5 mins

Scopes for reusable queries in Ruby on Rails - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a scope in Rails?
A scope is a way to define reusable, named queries in a Rails model. It helps keep code clean by grouping common query logic.
Click to reveal answer
beginner
How do you define a simple scope in a Rails model?
Use the scope method with a name and a lambda. Example: <br>scope :active, -> { where(active: true) }
Click to reveal answer
beginner
Why use scopes instead of repeating query code?
Scopes make code easier to read, maintain, and reuse. They avoid repeating the same query logic in many places.
Click to reveal answer
intermediate
Can scopes accept parameters? How?
Yes. You can pass parameters to scopes by using lambdas with arguments. Example: <br>scope :created_after, ->(date) { where('created_at > ?', date) }
Click to reveal answer
intermediate
How do scopes chain together in Rails?
Scopes return ActiveRecord relations, so you can chain them like methods. Example: <br>User.active.created_after(Date.today) runs both queries together.
Click to reveal answer
What does a Rails scope return?
AA SQL string
BAn ActiveRecord relation
CA plain Ruby array
DA controller action
How do you define a scope named 'recent' that returns records created in the last 7 days?
Ascope :recent, -> { where('created_at >= ?', 7.days.ago) }
Bdef recent; where('created_at >= ?', 7.days.ago); end
Cscope recent = where('created_at >= ?', 7.days.ago)
Dscope :recent { where('created_at >= ?', 7.days.ago) }
Which is a benefit of using scopes?
AThey speed up the database
BThey replace migrations
CThey make queries reusable and readable
DThey handle user authentication
Can you chain multiple scopes in Rails?
AYes, scopes return relations that can be chained
BNo, scopes must be called separately
COnly if they have no parameters
DOnly inside controllers
How do you pass a parameter to a scope?
AParameters are not supported in scopes
BDefine a method instead of a scope
CUse a global variable inside the scope
DUse a lambda with an argument, e.g., <code>scope :by_status, ->(status) { where(status: status) }</code>
Explain what a scope is in Rails and why it is useful.
Think about how you can avoid repeating the same query code.
You got /4 concepts.
    Describe how to define a scope that accepts a parameter and how to use it.
    Remember scopes are like methods that return queries.
    You got /4 concepts.