What is scope/named_scope in rails?
Asked Answered
C

4

113

I've recently started an internship. My employer uses ruby on rails, and I frequently encounter new syntax that I need to look up to understand. I've googled around for a good explanation of named_scope, but what I've found so far is mostly blog posts giving high praise for it, rather a straight definition or introduction.

What exactly is named_scope (now simply called scope) in ruby on rails?

Chapatti answered 2/2, 2011 at 1:42 Comment(4)
possible duplicate of What's the significance of named scope in Rails?Thickleaf
This blog post was invaluable to me when learning named scopes: ryandaigle.com/articles/2008/8/20/…Dessiatine
@notapatch the link is dead do you have another one?Professional
Ryan Daigle: Named Scope: It's Not Just for Conditions, Ya Know?: web.archive.org/web/20160306110506/http://…Ontario
A
220

A scope is a subset of a collection. Sounds complicated? It isn't. Imagine this:

You have Users. Now, some of those Users are subscribed to your newsletter. You marked those who receive a newsletter by adding a field to the Users Database (user.subscribed_to_newsletter = true). Naturally, you sometimes want to get those Users who are subscribed to your newsletter.

You could, of course, always do this:

User.where(subscribed_to_newsletter: true).each do #something

Instead of always writing this you could, however, do something like this.

#File: users.rb
class User < ActiveRecord::Base
  scope :newsletter, where(subscribed_to_newsletter: true)
  #yada yada
end

If you're using Rails 4 or newer, do this instead:

#File: users.rb
class User < ActiveRecord::Base
  scope :newsletter, -> { where(subscribed_to_newsletter: true) }
  #yada yada
end

This allows you to access your subscribers by simply doing this:

User.newsletter.each do #something

This is a very simple example but in general scopes can be very powerful tools to easy your work.

Check out this link: API Description

Appear answered 2/2, 2011 at 2:17 Comment(5)
Can I ask whats the advantages of this over say defining a method in the User Class called 'subscribedUsers'? e.g. 'def self.subscribedUsers self.where(:subscribed_to_newsletter => true) endNitrate
@Nitrate the advantage is the scope syntax is much cleaner, you get the same result but with just one lineCamden
@Nitrate There used to be a big efficiency advantage, as scopes would query the database lazily while methods would do it eagerly. In Rails 3, methods got lazy too, so now the difference is more syntactic. SourceGrous
API doc link is broken please update api.rubyonrails.org/classes/ActiveRecord/Scoping/Named/…Lie
Also allows using scoped routes linkCapacious
R
34

scope in active record is like class methods but they return Relation object which means you can call another scope or active record querying method on it.

For example, if you have a Zombie model (zombies table) with below mentioned scope methods,

class Zombie
  scope :rotting, -> { where(rotting: true) }
  scope :fresh, -> { where('age < ?', 25) }
  scope :recent, -> { order(created_at: :desc) }
end

And you call

Zombie.rotting.fresh.recent.limit(3)

It translates to the below in SQL,

select "zombies.*" from "zombies" where "zombies"."rotting" = 't' and (age<20) order by create_at desc limit 3

Example above is based on rails 4 syntax

Rove answered 24/9, 2014 at 17:23 Comment(1)
I can't find an example of order(:created_at, :desc) in any documentation. Is it possible you meant scope :recent, -> { order(created_at: :desc) } ? apidock.com/rails/v4.2.9/ActiveRecord/QueryMethods/orderOntario
A
7

The best way to understand about the details is to go to API Documentation.

You'll get the complete details and the ways we can use Scopes.

API Documentation of Scope

Alake answered 14/5, 2013 at 11:0 Comment(0)
B
1
  • Imagine you have a model: Person.

Now imagine you :

  • want all the people in the world who have red hair.
  • want all the people in the world who play cricket

You could get those particular classes of people by using a scope!

Person.red_hair.cricket ## finds all people with red hair who play cricket
Person.red_hair ## finds all people with red hair
Person.cricket ## finds all people who play cricket.

Now that wasn't so hard was it?

Bemis answered 27/6, 2016 at 5:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.