2

I have a simple DB query that is checking if a particular field does not contain 3x strings:

scope :not_abc, -> {
    where.not(name: ['A', 'B', 'C'])
}

The field in question is just a string with no default value, from schema.rb:

t.string   "name",     limit: 255

The problem is that the query above only returns fields that are non-nil, for example:

Returned objects:

name = ""
OR
name = "<any string NOT A,B,C>" 

Ignored objects:

name = nil
OR
name = "A" or "B" or "C"

Is there any way to build a rails query that searches with an array of strings but includes nil values in the results?

What should be returned:

name = nil
OR
name = ""
OR
name = "<any string NOT A,B,C>" 
5
  • where("name NOT IN (?) OR name = ?" ['A', 'B', 'C'], nil) add this. Commented Aug 19, 2016 at 17:43
  • ... Or using arel instead of strings. Commented Aug 19, 2016 at 17:48
  • @Arup Rakshit: Unfortunately, that returned the same results as where.not(name: ['A', 'B', 'C']) Commented Aug 19, 2016 at 17:49
  • so you meant OR name = ? has no effect. Commented Aug 19, 2016 at 17:51
  • Right, it had no effect to include OR name = ? Commented Aug 19, 2016 at 17:54

1 Answer 1

2

Got the same issue and found the solution here

Here is your scope in a version that should work.

scope :not_abc, -> {
    where("name NOT IN (?) OR name IS NULL", ['A', 'B', 'C'])
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.