How to use named scopes in Rails

In this tutorial I will show you how you can use named scopes to make querying the database even more easier.

I will describe named scopes as methods defined by the user inside a certain model.

You can find the models inside your app/models folder.

Here’s what it looks like the first time you open it up:

class Subjects < ActiveRecord::Base

end

To define a scope, just type in ‘scope’ followed by :methodname. Then comma followed by your condition.

scope :visible, where(:visible => true )

By just looking we already know that what we are querying here is the field called visible. And every time the visible method is called, it will return an array of all the records which has a true value in the field called visible.

Here’s how to call it from the rails console. Note that s here is a user defined variable, you can name it anything you want. Then Subjects is the name of the model but you need to capitalize the first letter to stick with the rules defined by Rails.

s = Subjects.visible

Here’s the result:

image

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s