Rails name_scope 作为 AR::Base 的扩展
class SomeModel < ActiveRecord::Base
named_scope :recent, lambda { { :conditions => ['created_at > ?', 1.week.ago] } }
end
我想扩展 AR::Base 类以使所有模型都具有此named_scope,我该如何做到这一点?
class SomeModel < ActiveRecord::Base
named_scope :recent, lambda { { :conditions => ['created_at > ?', 1.week.ago] } }
end
I want to extend the AR::Base class to have this named_scope for all models, how I can do this ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 config/initializers 中创建一个新的初始化程序文件,然后重新打开 ActiveRecord 的
Base
类以添加命名范围:— 当然,如果您尝试这样做,您会收到一个相当难看的错误在没有
created_at
属性的模型上使用此命名范围...Create a new initializer file in config/initializers and then re-open ActiveRecord's
Base
class to add the named scope:—Of course you get a rather ugly error should you attempt to use this named scope on a model that doesn't have a
created_at
attribute...