Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Rails doesn't <em>evaluate</em> the query until you actually try to access the results. Calling <code>Model.where</code> just returns an <code>ActiveRecord::Relation</code> onto which you can chain additional <code>where</code>/<code>order</code>/etc calls.</p> <p>Try this (<code>.all</code> forces the query to be evaluated and returns an array of results):</p> <pre><code>def self.my_func Interest.where(id: [1,2]).all end </code></pre> <p>Note that should shouldn't actually do this. It's much better for your model to just allow the <code>ActiveRecord::Relation</code> to be returned from the method, so the calling code can apply additional scoping/ordering methods to it.</p> <p>Also note that, instead of manually building an <code>id in (?)</code> query, Rails is smart enough to do it for you if you just use <code>where(id: [1,2])</code>.</p> <hr> <p>Bonus notes:</p> <p>On the terminal, the results get evaluated from <code>Model.where</code> immediately because IRB invokes <code>inspect</code> on the result of each expression you enter so it has something to print, and the returned <code>ActiveRecord::Relation</code> evaluates its query when inspected. You can bypass this to prove the point to yourself by adding <code>;nil</code>, so that your statement evaluates to <code>nil</code>; note that the <code>SELECT</code> doesn't happen until I manually call <code>x.inspect</code>:</p> <pre><code>irb(main):008:0&gt; x = User.where("name like 'bob'"); nil =&gt; nil irb(main):009:0&gt; x.inspect User Load (0.5ms) SELECT "users".* FROM "users" WHERE (name like 'bob') =&gt; "[]" </code></pre>
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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