ruby-on-rails-3 – 我可以在Rails中使用常用的ActiveRecord范围
发布时间:2020-12-17 04:18:47 所属栏目:百科 来源:网络整理
导读:在rails3中,我在模型中制作相同的范围.例如 class Common ActiveRecord::Base scope :recent,order('created_at DESC') scope :before_at,lambda{|at| where("created_at ?",at) } scope :after_at,lambda{|at| where("created_at ?",at) }end 我想将公共范
在rails3中,我在模型中制作相同的范围.例如
class Common < ActiveRecord::Base scope :recent,order('created_at DESC') scope :before_at,lambda{|at| where("created_at < ?",at) } scope :after_at,lambda{|at| where("created_at > ?",at) } end 我想将公共范围拆分为lib中的模块.所以我试试这个. module ScopeExtension module Timestamps def self.included(base) base.send :extend,ClassMethods end module ClassMethods scope :recent,lambda{order('created_at DESC')} scope :before_at,at) } scope :after_at,at) } end end 我写了这个 class Common < ActiveRecord::Base include ScopeExtension::Timestamps end 但是Rails显示了这个错误. undefined method `scope' for ScopeExtension::Timestamps::ClassMethods:Module (我没有忘记自动加载库) 如何在活动记录中轻松重用常用范围功能? 我猜这个问题与加载序列有关.但我没有任何想法要解决. 解决方法
我解决了这个调用self.included(class)的范围:
module Timestamps def self.included(k) k.scope :created_yesterday,k.where("created_at" => Date.yesterday.beginning_of_day..Date.yesterday.end_of_day) k.scope :updated_yesterday,k.where("created_at" => Date.today.beginning_of_day..Date.today.end_of_day) k.scope :created_today,k.where("created_at" => Date.today.beginning_of_day..Date.today.end_of_day) k.scope :updated_today,k.where("created_at" => Date.today.beginning_of_day..Date.today.end_of_day) end end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |