Request for all users except for users with an identifier in this collection

I try to find all users except users with an id that is a member of an array exclude_ids

Here is what I have:

User.where("id != ?", exclude_ids)

This only works when exclude_ids has only 1 element. If it has more than one item, I get

this error:

ActiveRecord::StatementInvalid: SQLite3::SQLException: near ",": syntax error: SELECT     "users".* FROM       "users" WHERE     (id != 1,2)

I would appreciate any help.

+3
source share
3 answers

I have not used Rails 3, but it is unsafe to use User.where("id in #{exclude_ids} ?").

In Rails 2.x, you do it like this

User.find(:all, :conditions => ["id NOT IN (?)", [1,2,3]])

Rails 3.x docs http://railsapi.com/doc/rails-v3.0.0.beta.3/classes/ActiveRecord/Base.html

+5
User.where('id NOT IN (:ids)', ids: exclude_ids)  # SQL does the filtering

User.select { |u| exclude_ids.exclude? u.id }  # Ruby does the filtering
+2

,

User.where ("id not in # {exclude_ids}?")

0
source

Source: https://habr.com/ru/post/1754058/


All Articles