Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I've hit the same problem looking for an activerecord alternative to mongoid's <code>#any_of</code>.</p> <p>@jswanner answer is good, but will only work if the where parameters are a Hash :</p> <pre><code>&gt; User.where( email: 'foo', first_name: 'bar' ).where_values.reduce( :and ).method( :or ) =&gt; #&lt;Method: Arel::Nodes::And(Arel::Nodes::Node)#or&gt; &gt; User.where( "email = 'foo' and first_name = 'bar'" ).where_values.reduce( :and ).method( :or ) NameError: undefined method `or' for class `String' </code></pre> <p>To be able to use both strings and hashes, you can use this :</p> <pre><code>q1 = User.where( "email = 'foo'" ) q2 = User.where( email: 'bar' ) User.where( q1.arel.constraints.reduce( :and ).or( q2.arel.constraints.reduce( :and ) ) ) </code></pre> <p>Indeed, that's ugly, and you don't want to use that on a daily basis. Here is some <code>#any_of</code> implementation I've made : <a href="https://gist.github.com/oelmekki/5396826" rel="nofollow">https://gist.github.com/oelmekki/5396826</a></p> <p>It let do that :</p> <pre><code>&gt; q1 = User.where( email: 'foo1' ); true =&gt; true &gt; q2 = User.where( "email = 'bar1'" ); true =&gt; true &gt; User.any_of( q1, q2, { email: 'foo2' }, "email = 'bar2'" ) User Load (1.2ms) SELECT "users".* FROM "users" WHERE (((("users"."email" = 'foo1' OR (email = 'bar1')) OR "users"."email" = 'foo2') OR (email = 'bar2'))) </code></pre> <p>Edit : since then, I've published <a href="https://github.com/oelmekki/activerecord_any_of" rel="nofollow">a gem to help building OR queries</a>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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