what is the difference between named_scope and met

2019-08-17 18:53发布

named_scope or scope how difference with class method.

named_scope :active, :conditions => {:status => 'Active'}

def self.active
  self.find(:all, :conditions => {:status => 'Active'}
end

Whats the difference between the two?

2条回答
你好瞎i
2楼-- · 2019-08-17 19:12

In the end 'scope' will define a chainable class method on your model. That's why every class method, that returns a 'scope' (which is an object of the class ActiveRecord::Relation) can be used in the same way a definied scope / named_scope can.

If you want to find our more about scopes, I recommend using the rails console to play a bit with the ouput, or - maybe as a start - read the rails guides - they pretty much explain it: http://guides.rubyonrails.org/active_record_querying.html#scopes

edit:

Oh, and of course reading into the rails code can often clear up things quicker, then anyone or anything else. If you look at the definition of the 'scope' method here: https://github.com/rails/rails/blob/master/activerecord/lib/active_record/scoping/named.rb#L159 you will see, how it's defining a method (on class level) - which is pretty similar to defining the method yourself, as in your example.

查看更多
放荡不羁爱自由
3楼-- · 2019-08-17 19:12

The big difference is chainability. Let's say you have another named scope, popular:

named_scope :popular, :conditions => { :popular => true }

Let's say you want to get popular active users. So you say User.popular.active

named_scope :active, :conditions => {:status => 'Active'}

In this case, then User.popular.active works.

On the other hand,

def self.active
  self.find(:all, :conditions => {:status => 'Active'}
end

may allow you to say User.active.popular (depending on your rails version, IIRC), but definitely not User.popular.active.

Informally, the scope method arranges for the method it's defining to be available on other scopes of the object. Defining a class method does not.

查看更多
登录 后发表回答