范围不适用于 Mongoid(未定义方法“to_criteria”)

new*_*ike 1 mongoid ruby-on-rails-4 mongoid4

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

并得到以下错误

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

发布_schedule.rb

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

mu *_*ort 5

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

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

并将其用作:

# The `first` goes here instead.
r = ReleaseSchedule.next_release.first
Run Code Online (Sandbox Code Playgroud)

但实际上,您只需要一个类方法:

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

scope毕竟,宏只是构建类方法的一种奇特方式。我们唯一的原因scope是表达一个意图(即逐段构建查询),而您正在做的事情与该意图不符。