在Rails 4中共享命名范围

时间:2014-06-25 14:21:48

标签: ruby-on-rails

我正在尝试通过模块在两个模型之间共享命名范围。它不适合我。我一直收到一个未定义的错误。我正在尝试使用空的'your_scope'范围:

配置/初始化/ boxshare_init.rb

require 'assets/named_scopes/m.rb'

LIB /资产/ named_scopes / m.rb

module M
  def self.included(base)
    base.class_eval do
      scope :your_scope, lambda {}
    end
  end
end

应用程序/模型/ folder.rb

class Folder < ActiveRecord::Base       
    include M

    acts_as_tree

    belongs_to :user
    has_many :assets, dependent: :destroy
end

rails console: $ rails c

Loading development environment (Rails 4.1.1) irb: warn: can't alias
context from irb_context.
2.0.0-p0 :001 > Folder.last.your_scope  
Folder Load (0.1ms)  SELECT  "folders".* FROM "folders"   ORDER BY "folders"."id" DESC LIMIT 1
NoMethodError: undefined method `your_scope' for <Folder:0x007fd781a1daf0>

我哪里错了?

1 个答案:

答案 0 :(得分:0)

ActiveRecord方法.last返回模型的实例,而不是AR :: Relation,它可以链接范围。

试试这个:

Folder.last.class
# => Folder
Folder.your_scope.class
# => ActiveRecord::Relation

像这样使用your_scope

Folder.your_scope.last