Ruby on the rails

From Agile Web Development With Rails

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

   named_scope :checks, :conditions => {:pay_type => :check}
end

Statement

orders = Orders.checks.last_n_days(7)

will result in only one query per database.

How do rails realize this? I am new to Ruby, and I wonder if there is a special construct that allows this to happen.

In order to be able to cling to such methods, the functions generated by named_scope must return themselves or an object, as far as possible. But how does Ruby know that this is the last function call and that he should query the database now?

I ask this because the above statement is actually querying the database, not just returning the SQL statement that results from the chain.

+3
source share
3 answers

named_scope ( , ).

- ActiveRecord:: NamedScope:: Scope, AR. , , , - .

Lazy loading - ( - ) scopes , , . , , .

: , ( - , - ) IRB. , Enter, , , , inspect . , Scope, IRB inspect , . , inspect , .

+7

,

class Order < ActiveRecord::Base

  class << self
    def last_n_days(n)
      scoped(:conditions => ['updated < ?', days])
    end
    def checks
      scoped(:conditions => {:pay_type => :check})
    end
  end

end

@orders = Order.last_n_days(5)
@orders = Order.checks
@orders = Order.checks.last_n_days(5)

, . , , . : Rails 3 !

+3

Very cool. I was thinking of doing something similar in Javascript, but Javascript is behaving quite strangely.

Statement:

var x = SomeObject;

does not call the SomeObject toString () function. But the statement:

var x;
x = SomeObject;

calls the toString () function correctly as expected.

This prevents Javascript from doing cool things with chaining. = (

0
source

Source: https://habr.com/ru/post/1740455/


All Articles