i'm trying create mongoid query records match date range, or have nil values. here ruby code performs function turn mongoid query:
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
how can improve performance turning method mongoid query?
update:
here rspec test i'm using verify correct behavior:
describe '.active' 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') } 'returns enabled , within current time' 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
maybe trick:
where( enabled: true, {:$or => [{start_date: nil}, {:start_date.lte => date.today.to_time }]}, {:$or => [{end_date: nil}, {:end_date.gte => date.tomorrow.to_time}]} )
Comments
Post a Comment