title: Where chains or similar in Rails to narrow results
body: <p>How do you narrow results from a table in Rails?</p>
  <p>I'm using Rails 4.0.2 and PostgreSQL and can do</p>
  <pre><code>users = User.where(:flag1).where(:flag2 =&gt; nil)
  </code></pre>
  <p>but not</p>
  <pre><code>users = User.where(:flag1).where(:flag2 =&gt; nil).where(:flag3 =&gt; nil)
  </code></pre>
  <p>to get</p>
  <pre><code>#&lt;ActiveRecord::Relation []&gt;
  </code></pre>
  <p>Am I missing something?</p>
  <p>I've tried with Squeel, and can similarly do</p>
  <pre><code>users = User.where{(flag1) &amp; (flag2 == nil)}
  </code></pre>
  <p>but not</p>
  <pre><code>users = User.where{(flag1) &amp; (flag2 == nil) &amp; (flag3 == nil)}
  </code></pre>
  <p>which yields</p>
  <pre><code>!! #&lt;TypeError: Cannot visit Squeel::Nodes::Predicate&gt;
  </code></pre>
  <p>Any ideas on how to do this with and/or without Squeel? Thanks!</p>
  <h1>UPDATE</h1>
  <p>The problem for the normal query is caused by the fact that the flag2 and flag3 values can be  either nil or false. I tried to take that into account with Squeel.</p>
  <p>I can do</p>
  <pre><code>User.where{(flag1) &amp; ((flag2.eq nil) | (flag2.eq false))}
  </code></pre>
  <p>but not</p>
  <pre><code>User.where{(flag1) &amp; ((flag2.eq nil) | (flag2.eq false)) &amp; ((flag3.eq nil) | (flag3.eq false))}
  </code></pre>
  <p>which returns</p>
  <pre><code>!! #&lt;TypeError: Cannot visit Squeel::Nodes::Or&gt;
  </code></pre>