What is the meaning of the named area in Rails?

Before proceeding to the details.

Question 1: - What is the scope here (i.e. named ** scope )? **

What are the benefits of using a named scope?

Now: -

from Agile Development's book with Rails: -

class Order < ActiveRecord::Base named_scope :last_n_days, lambda { |days| {:conditions => ['updated < ?' , days] } } named_scope :checks, :conditions => {:pay_type => :check} end 

Such a named area will allow us to find the value of snap orders last week.

  orders = Orders.last_n_days(7) 

Areas can also be combined.

 orders = Orders.checks.last_n_days(7) 

why we use named_scope here. We can do the same with methods. What special thing we got with named_scope.

+2
ruby-on-rails
May 27 '10 at 9:00 a.m.
source share
3 answers

A sphere simply means some selected range. Therefore, if you use:

 orders = Orders.checks.last_n_days(7) 

then you want to select from orders only those orders that are paid by check and are within the last 7 days. Thus, you fulfill the "orders".

Why not use the methods?

Named scopes are methods. This is just an easier way to define them, so you don’t need to take care of all the details and you can be happy to use it!

And remember that scopes simply add some conditions (and others) to the sql query.

+2
May 27 '10 at 10:22
source share

we get shorter, chainier, and more readable code:

 orders = Orders.checks.last_n_days(7) 

much more readable, shorter and not bound than

 orders = Orders.all :conditions => ["updated < ? and pay_type='check'", 7] 

In Rails3, the advantage will be even greater due to arel . For more information, I recommend watching Railscasts:

+3
May 27 '10 at 9:19
source share

Named_scope is really useful for 2 cases

improved readability

With a good scope_name, you can more easily understand what you want to really look for.

Chaining

All named_scope can be bound. Therefore, if you want to create a search engine, this is easy to do. Did it before it hurt.

You can generate a chain on the fly.

+2
May 27 '10 at 9:17
source share



All Articles