From the course: Ruby on Rails Models and Associations

Unlock the full course today

Join today to access over 24,200 courses taught by industry experts.

Named scopes

Named scopes

- [Instructor] In this movie, we will learn how to use named scopes in our models. When we discussed model design at the beginning of this chapter, we saw the benefits of moving commonly used logic into the models. Named scopes follow that principle. And they allow us to define commonly used queries in our models. You construct them out of the built-in query methods that we've been using, but they're stored as lambda functions, which create a block of code for later use. You won't use lambda functions often, but named scopes require them, and they're easy to learn. In this example, the Product class has a named scope. It uses the keyword scope, followed by a symbol for the name that we want to give it. And then there's a comma and an arrow created from a minus and a greater than sign. That arrow indicates that the block inside the curly braces is a lambda function. It holds code to be used later. We can use our named…

Contents