小编neo*_*oin的帖子

我可以在Rails中使用常用的ActiveRecord范围(范围)和模块吗?

在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
Run Code Online (Sandbox Code Playgroud)

我想将公共范围拆分为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   , lambda{|at| where("created_at < ?" , at) }
      scope :after_at    , lambda{|at| where("created_at > ?" , at) }
    end
end
Run Code Online (Sandbox Code Playgroud)

我写这个

class Common < ActiveRecord::Base
  include ScopeExtension::Timestamps
end
Run Code Online (Sandbox Code Playgroud)

但是Rails显示了这个错误. …

activerecord scope ruby-on-rails-3

7
推荐指数
2
解决办法
2910
查看次数

标签 统计

activerecord ×1

ruby-on-rails-3 ×1

scope ×1