【问题标题】:scope not working on Mongoid (undefined method `to_criteria')范围不适用于 Mongoid(未定义的方法 `to_criteria')
【发布时间】:2015-01-17 03:14:08
【问题描述】:

我在其他控制器中调用ReleaseSchedule.next_release

并得到以下错误

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

releae_schedule.rb

class ReleaseSchedule
  scope :next_release, ->(){ ReleaseSchedule.where(:release_date.gte => Time.now).without(:_id, :created_at, :updated_at).first }
end

【问题讨论】:

    标签: ruby-on-rails-4 mongoid mongoid4


    【解决方案1】:

    这根本不是一个真正的作用域,它只是一个封装起来看起来像一个作用域的类方法。有两个问题:

    1. 你说的是ReleaseSchedule.where(...),所以你不能链接“范围”(即ReleaseSchedule.where(...).next_release不会做它应该做的事情)。
    2. 您的“范围”以 first 结尾,因此它不会返回查询,而只会返回一个实例。

    2 可能是您的 NoMethodError 的来源。

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

    # 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 的唯一原因是表达一个意图(即逐个构建查询),而您所做的与该意图不符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-11
      • 1970-01-01
      • 2013-05-20
      • 1970-01-01
      • 2012-04-01
      • 2021-12-19
      相关资源
      最近更新 更多