where condition with array

Rails 3.2.11

Say, my app needs special conditions like

        plans = Plan.arel_table         @plan = Plan.where(                                  plans[:user_id].not_eq(3)                             ).where(                                  plans[:user_id].not_eq(4)                             ).where(                                  plans[:user_id].not_eq(7)                             )...

If many not_eq conditions are needed, the way written like this is inefficient.

Is there anyway to write this in a more concise way?

soichi

Have you considered doing a sql query?

my approach would be this

query_array = [3,4,7].each do |value|   query_array << "user_id != #{value}" end

Plan.where("#{query_array}.join(" and ")")

Also, the past week I found this gist from ryan

I'm still analyzing it but it taught me a lot

Javier

If going the SQL route, easier might be:

Plan.where("user_id not in (3,4,7)")

thanks. I haven't done sql query at all but this time I did for the first time.

soichi

Try something like this:

Plan.where(“user_id not in (#{[3,4,7].join(', ')})”)

This easier, and won’t risk SQL injection if that array has user-generated content:

Plan.where(‘user_id NOT IN ?’, [3,4,7])

–Matt Jones

Slight correction:

Plan.where('user_id NOT IN (?)', [3,4,7])