Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails where not equals *any* of array of values

Tags:

activerecord

I've tried to do stuff like this

not_allowed = ['5', '6', '7']
sql = not_allowed.map{|n| "col != '#{n}'"}.join(" OR ")
Model.where(sql)

and

not_allowed = ['5', '6', '7']
sql = not_allowed.map{|n| "col <> '#{n}'"}.join(" OR ")
Model.where(sql)

but both of these just return my entire table which isn't accurate.

So I've done this and it works:

shame = values.map{|v| "where.not(:col => '#{v}')"  }.join(".")
eval("Model.#{shame}")

and I'm not even doing this for an actual web application, I'm just using rails for its model stuff. So there aren't any actual security concerns for me. But this is an awful fix and I felt obligated to post this question

like image 294
boulder_ruby Avatar asked Nov 19 '25 05:11

boulder_ruby


1 Answers

Your first pieces of code do not work because the OR condition is making the entire where clause be always true. That is, if the value of col is 5, 5 is not different than 5, but it is different than 6 and 7, therefore, the where clause is evaluating as: false OR true OR true which returns true.

I think in this case you can use the NOT IN clause instead, as follows:

not_allowed = ['1','2', '3']
Model.where('col not in (?)', not_allowed)

This will return all records except the ones where col matches any of the elements in your array.

like image 117
apanosa Avatar answered Nov 22 '25 03:11

apanosa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!