Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can try to compose your criteria using Mongoid's query methods and dereferencing into the criteria's selector, but I wouldn't necessarily recommend this -- see below for an example. I second the recommendation to craft your third scope. Remember that these scopes correspond to db queries that you want to be efficient, so it is probably worth your time to examine and understand the resulting and underlying MongoDB queries that are generated.</p> <p>Model</p> <pre><code>class Episode include Mongoid::Document field :name, type: String field :start_time, type: Time field :end_time, type: Time scope :upcoming, -&gt; { where(:start_time.gt =&gt; Time.now).asc(:start_time) } scope :in_progress, -&gt; { now = Time.now where(:start_time.lte =&gt; now).where(:end_time.gte =&gt; now).asc(:start_time) } scope :current, -&gt; { any_of([upcoming.selector, in_progress.selector]) } scope :current_simpler, -&gt; { where(:end_time.gte =&gt; Time.now) } end </code></pre> <p>Test</p> <pre><code>require 'test_helper' class EpisodeTest &lt; ActiveSupport::TestCase def setup Episode.delete_all end test "scope composition" do #p Episode.in_progress #p Episode.upcoming #p Episode.current #p Episode.current_simpler in_progress_name = 'In Progress' upcoming_name = 'Upcoming' Episode.create(:name =&gt; in_progress_name, :start_time =&gt; Time.now, :end_time =&gt; 1.hour.from_now) Episode.create(:name =&gt; upcoming_name, :start_time =&gt; 1.hour.from_now, :end_time =&gt; 2.hours.from_now) assert_equal([in_progress_name], Episode.in_progress.to_a.map(&amp;:name)) assert_equal([upcoming_name], Episode.upcoming.to_a.map(&amp;:name)) assert_equal([in_progress_name, upcoming_name], Episode.current.to_a.map(&amp;:name)) assert_equal([in_progress_name, upcoming_name], Episode.current_simpler.to_a.map(&amp;:name)) end end </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload