named_scope或范围与类方法的区别。named_scope和method有什么区别?
named_scope :active, :conditions => {:status => 'Active'}
def self.active
self.find(:all, :conditions => {:status => 'Active'}
end
这两者有什么区别?
named_scope或范围与类方法的区别。named_scope和method有什么区别?
named_scope :active, :conditions => {:status => 'Active'}
def self.active
self.find(:all, :conditions => {:status => 'Active'}
end
这两者有什么区别?
最后'范围'将在您的模型上定义一个可链接的类方法。这就是为什么每个返回'范围'的类方法(它是类ActiveRecord :: Relation的一个对象)可以像定义的范围/ named_scope一样使用。
如果您想了解我们更多的范围,我建议使用导轨控制台玩了一下与输出中,或 - 也许作为一个开始 - 读导轨导向 - 他们几乎解释:http://guides.rubyonrails.org/active_record_querying.html#scopes
编辑:
哦,当然读入rails代码往往可以更快地清理事情,然后任何人或其他任何东西。如果你看一下'范围'方法的定义:https://github.com/rails/rails/blob/master/activerecord/lib/active_record/scoping/named.rb#L159你会看到它是如何定义一个方法的(在课堂上) - 这和你自己定义方法很相似,就像你的例子。
最大的区别在于可链接性。比方说,你有另一个命名的范围,流行:
named_scope :popular, :conditions => { :popular => true }
假设你想获得流行的活跃用户。所以你说User.popular.active
named_scope :active, :conditions => {:status => 'Active'}
在这种情况下,然后User.popular.active
作品。
在另一方面,
def self.active
self.find(:all, :conditions => {:status => 'Active'}
end
可能让你说User.active.popular
(取决于你的Rails版本,IIRC),但绝对不是User.popular.active
。
非正式地,scope
方法安排它定义的方法在对象的其他范围上可用。定义类方法不。
我是什么语言? “ – Saintali 2012-08-05 11:54:15