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

痞子三分冷 提交于 2019-11-27 10:48:47

问题


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.


回答1:


This should work:

ids_to_exclude = [1,2,3]
items_table = Arel::Table.new(:items)

array_without_excluded_ids = Item.where(items_table[:id].not_in ids_to_exclude)

And it's fully object-oriented with no strings :-)




回答2:


Rails 4 solution:

ids_to_exclude = [1,2,3]
array_without_excluded_ids = Item.where.not(id: ids_to_exclude)



回答3:


You can also use Squeel gem to accomplish such query. Documentation of it, goes here



来源:https://stackoverflow.com/questions/4581376/how-to-exclude-an-array-of-ids-from-query-in-rails-using-activerecord

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!