我正在尝试为匹配特定日期范围或具有 nil 值的记录创建 Mongoid 查询。这是我的 ruby 代码,它执行我想变成 Mongoid 查询的功能:
class MyModel
include Mongoid::Document
field :name
field :enabled, type: Boolean, default: false
field :start_date, type: DateTime
field :end_date, type: DateTime
def self.active
documents = where(enabled: true)
documents = documents.keep_if {|doc| doc.start_date.nil? || doc.start_date <= Date.today}
documents = documents.keep_if {|doc| doc.end_date.nil? || doc.end_date >= Date.tomorrow}
documents
end
end
如何通过将此方法转换为 Mongoid 查询来提高性能?
更新:
这是我用来验证正确行为的 RSpec 测试:
describe '.active' do
let!(:disabled){ Fabricate(:model, enabled: false, name: 'disabled') }
let!(:enabled_without_date){ Fabricate(:active_model, name: 'enabled_without_date') }
let!(:past){ Fabricate(:active_model, start_date: 1.week.ago, end_date: Date.yesterday, name: 'past') }
let!(:current){ Fabricate(:active_model, start_date: Date.today, end_date: Date.tomorrow, name: 'current') }
let!(:future){ Fabricate(:active_model, start_date: Date.tomorrow, end_date: 1.week.from_now, name: 'future') }
it 'returns only enabled and within the current time' do
MyModel.count.should == 5
models = MyModel.active.to_a
models.should_not be_empty
models.should_not include disabled
models.should_not include past
models.should_not include future
models.should include enabled_without_date
models.should include current
end
end