Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exclude an array of ids from query in Rails (using ActiveRecord)?

Tags:

I would like to perform an ActiveRecord query that returns all records except those records that have certain ids. The ids I would like excluded are stored in an array. So:

ids_to_exclude = [1,2,3] array_without_excluded_ids = Item. ??? 

I'm not sure how to complete the second line.

Background: What I've already tried:

I'm not sure background is necessary, but I've already tried various combinations of .find and .where. For example:

array_without_excluded_ids = Item.find(:all, :conditions => { "id not IN (?)", ids_to_exclude }) array_without_excluded_ids = Item.where( "items.id not IN ?", ids_to_exclude) 

These fail. This tip might be on the right track, but I have not succeeded in adapting it. Any help would be greatly appreciated.

like image 202
CuriousYogurt Avatar asked Jan 03 '11 00:01

CuriousYogurt


1 Answers

Rails 4 solution:

ids_to_exclude = [1,2,3] array_without_excluded_ids = Item.where.not(id: ids_to_exclude) 
like image 107
nslocum Avatar answered Oct 15 '22 14:10

nslocum