ruby-on-rails-3 – 我可以在Rails中使用常用的ActiveRecord范围(范围)和模块吗?

前端之家收集整理的这篇文章主要介绍了ruby-on-rails-3 – 我可以在Rails中使用常用的ActiveRecord范围(范围)和模块吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在rails3中,我在模型中制作相同的范围.例如
  1. class Common < ActiveRecord::Base
  2. scope :recent,order('created_at DESC')
  3. scope :before_at,lambda{|at| where("created_at < ?",at) }
  4. scope :after_at,lambda{|at| where("created_at > ?",at) }
  5. end

我想将公共范围拆分为lib中的模块.所以我试试这个.

  1. module ScopeExtension
  2. module Timestamps
  3. def self.included(base)
  4. base.send :extend,ClassMethods
  5. end
  6.  
  7. module ClassMethods
  8. scope :recent,lambda{order('created_at DESC')}
  9. scope :before_at,at) }
  10. scope :after_at,at) }
  11. end
  12. end

我写了这个

  1. class Common < ActiveRecord::Base
  2. include ScopeExtension::Timestamps
  3. end

但是Rails显示了这个错误.

  1. undefined method `scope' for ScopeExtension::Timestamps::ClassMethods:Module

(我没有忘记自动加载库)

如何在活动记录中轻松重用常用范围功能

我猜这个问题与加载序列有关.但我没有任何想法要解决.
提示我.

解决方法

解决了这个调用self.included(class)的范围:
  1. module Timestamps
  2. def self.included(k)
  3. k.scope :created_yesterday,k.where("created_at" => Date.yesterday.beginning_of_day..Date.yesterday.end_of_day)
  4. k.scope :updated_yesterday,k.where("created_at" => Date.today.beginning_of_day..Date.today.end_of_day)
  5. k.scope :created_today,k.where("created_at" => Date.today.beginning_of_day..Date.today.end_of_day)
  6. k.scope :updated_today,k.where("created_at" => Date.today.beginning_of_day..Date.today.end_of_day)
  7. end
  8. end

猜你在找的Ruby相关文章