保持named_scope扩展干燥
在 Rails 中,您可以在 named_scope
后面添加一个块,用于其他上下文相关的方法,如下所示:
class User < ActiveRecord::Base
named_scope :inactive, :conditions => {:active => false} do
def activate
each { |i| i.update_attribute(:active, true) }
end
end
end
在本例中,activate
方法不是在 上定义的。 >User
类,但位于 ActiveRecord::NamedScope::Scope
对象上。
我有一系列的三个范围,需要具有相同的方法定义。为了不重复代码,我如何抽象该块,以便我可以定义它一次并将其传递给每个 named_scope
?
In Rails, you can add a block after a named_scope
for additional, context-sensitive methods like so:
class User < ActiveRecord::Base
named_scope :inactive, :conditions => {:active => false} do
def activate
each { |i| i.update_attribute(:active, true) }
end
end
end
In this example, the activate
method is being defined not on the User
class, but on the ActiveRecord::NamedScope::Scope
object.
I have a series of three scopes that need to have identical method definitions. In the interests of not repeating code, how would I abstract that block such that I could define it once and pass it to each named_scope
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,这是一个很好的问题——我不知道命名作用域的这个特性!以下对我有用:
您可以将
add_activate
块作为最后一个参数传递给任何需要activate
方法的命名范围。Firstly, great question--I didn't know about that feature of named scopes! The following works for me:
You can pass the
add_activate
block as the last argument to any named scopes that need theactivate
method.好多了:
http://tuxicity。 se/rails/dry/2009/01/04/share-named-scopes-in-rails.html
保存在您的
/lib
目录中(在 Rails 3 中的初始化程序中放置一个 require ) 并在您的User
类中包含 NamedScopeMuch better:
http://tuxicity.se/rails/dry/2009/01/04/share-named-scopes-in-rails.html
Save in your
/lib
directory (put a require in an initializers in rails 3) andinclude NamedScope
in yourUser
class