Question

How do you narrow results from a table in Rails?

I'm using Rails 4.0.2 and PostgreSQL and can do

users = User.where(:flag1).where(:flag2 => nil)

but not

users = User.where(:flag1).where(:flag2 => nil).where(:flag3 => nil)

to get

#<ActiveRecord::Relation []>

Am I missing something?

I've tried with Squeel, and can similarly do

users = User.where{(flag1) & (flag2 == nil)}

but not

users = User.where{(flag1) & (flag2 == nil) & (flag3 == nil)}

which yields

!! #<TypeError: Cannot visit Squeel::Nodes::Predicate>

Any ideas on how to do this with and/or without Squeel? Thanks!

UPDATE

The problem for the normal query is caused by the fact that the flag2 and flag3 values can be either nil or false. I tried to take that into account with Squeel.

I can do

User.where{(flag1) & ((flag2.eq nil) | (flag2.eq false))}

but not

User.where{(flag1) & ((flag2.eq nil) | (flag2.eq false)) & ((flag3.eq nil) | (flag3.eq false))}

which returns

!! #<TypeError: Cannot visit Squeel::Nodes::Or>
Was it helpful?

Solution

I'm now doing

User.where{(flag1)}.where{((flag2.eq nil) | (flag2.eq false))}.where{((flag3.eq nil) | (flag3.eq false))}

and that seems to work in the Rails console.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top