Ruby on rails 4 作用域在Mongoid上不起作用(未定义的方法`to#u准则';)

Ruby on rails 4 作用域在Mongoid上不起作用(未定义的方法`to#u准则';),ruby-on-rails-4,mongoid,mongoid4,Ruby On Rails 4,Mongoid,Mongoid4,我在其他控制器中调用ReleaseSchedule.next\u release 并得到以下错误 NoMethodError (undefined method `to_criteria' for #<ReleaseSchedule:0x007f9cfafbfe70>): app/controllers/weekly_query_controller.rb:15:in `next_release' 那根本不是一个真正的作用域,它只是一个包装成作用域的类方法。有两个问题: 你说的

我在其他控制器中调用
ReleaseSchedule.next\u release

并得到以下错误

NoMethodError (undefined method `to_criteria' for #<ReleaseSchedule:0x007f9cfafbfe70>):
  app/controllers/weekly_query_controller.rb:15:in `next_release'

那根本不是一个真正的作用域,它只是一个包装成作用域的类方法。有两个问题:

  • 你说的是
    ReleaseSchedule.where(…)
    ,所以你不能链接“范围”(即
    ReleaseSchedule.where(…)。下一个发布版不会做它应该做的事情)
  • 您的“范围”以
    开头
    结束,因此它不会返回查询,只返回单个实例
  • 2可能就是你的命名错误的来源

    如果出于某种原因,你真的希望它成为一个范围,那么你会说:

    # No `first` or explicit class reference in here.
    scope :next_release, -> { where(:release_date.gte => Time.now).without(:_id, :created_at, :updated_at) }
    
    并将其用作:

    # The `first` goes here instead.
    r = ReleaseSchedule.next_release.first
    
    但实际上,您只需要一个类方法:

    def self.next_release
      where(:release_date.gte => Time.now).without(:_id, :created_at, :updated_at).first
    end
    

    毕竟,
    scope
    宏只是构建类方法的一种奇特方式。我们拥有
    作用域的唯一原因是表达一个意图(即逐块构建查询),而您所做的与该意图不匹配。

    这根本不是一个真正的作用域,它只是一个包装成作用域的类方法。有两个问题:

  • 你说的是
    ReleaseSchedule.where(…)
    ,所以你不能链接“范围”(即
    ReleaseSchedule.where(…)。下一个发布版不会做它应该做的事情)
  • 您的“范围”以
    开头
    结束,因此它不会返回查询,只返回单个实例
  • 2可能就是你的命名错误的来源

    如果出于某种原因,你真的希望它成为一个范围,那么你会说:

    # No `first` or explicit class reference in here.
    scope :next_release, -> { where(:release_date.gte => Time.now).without(:_id, :created_at, :updated_at) }
    
    并将其用作:

    # The `first` goes here instead.
    r = ReleaseSchedule.next_release.first
    
    但实际上,您只需要一个类方法:

    def self.next_release
      where(:release_date.gte => Time.now).without(:_id, :created_at, :updated_at).first
    end
    
    毕竟,
    scope
    宏只是构建类方法的一种奇特方式。我们拥有
    scope
    的唯一原因是表达一个意图(即逐段构建查询),而您所做的与该意图不匹配