× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Ruby: how to remove items from array A if it's not in array B?

Simone Carletti
Mar 21, 2015
<p>You can use the <code>IN</code> SQL statement.</p> <pre><code>list_of_students = Student.where('class = ? AND teacher_id IN (?)', param[:given_class], list_of_teachers.map(&amp;:id)) </code></pre> <p>If the <code>list_of_teachers</code> is an <code>ActiveRecord::Relation</code> (and not an array), you can also use <code>#pluck(:id)</code> or (from Rails 4) <code>#ids</code></p> <pre><code>Student.where('class = ? AND teacher_id IN (?)', param[:given_class], list_of_teachers.ids) </code></pre> <p>There are several ways to write the <code>IN</code> statement. Given you already have a <code>where</code>, I joined it to the main where. But you could also write</p> <pre><code>Student.where('class = ?', param[:given_class]).where(teacher_id: list_of_teachers) </code></pre> <p>or</p> <pre><code>Student.where(class: param[:given_class], teacher_id: list_of_teachers) </code></pre> <p>Also note you don't need to assign the list of teachers to a variable.</p> <pre><code>Student.where(class: param[:given_class], teacher_id: Teacher.where(...).ids) </code></pre> <p>Last but not least, if your <code>Teacher</code> query is simple, you may want to use a single query and a JOIN. Assume you want to get all the Teachers with name <code>Rose</code>.</p> <pre><code>Student.where(class: param[:given_class], teacher_id: Teacher.where(name: 'Rose').ids) </code></pre> <p>You can rewrite the same query to</p> <pre><code>Student.where(class: param[:given_class]).joins(:teacher).where(teacher: { name: 'Rose' }) </code></pre> <p>or (the final and shorter expression)</p> <pre><code>Student.joins(:teacher).where(class: param[:given_class], teacher: { name: 'Rose' }) </code></pre> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/27062891/Ruby:%20how%20to%20remove%20items%20from%20array%20A%20if%20it's%20not%20in%20array%20B?/27063082">Stack Overflow</a>.</p>
comments powered by Disqus