0

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>
Community
  • 1
  • 1
jiku
  • 283
  • 5
  • 16
  • Are you sure you're sharing the actual Rails code you've tried? `where` doesn't take a block, yet that's what you're showing (i.e. `where {...}`. – Peter Alfvin Dec 21 '13 at 17:12
  • Thanks and sorry about that. Updated the post. Should only be for squeel. – jiku Dec 21 '13 at 17:36
  • Could you share what output you're getting for the Rails case that doesn't produce what you're looking for? – Peter Alfvin Dec 21 '13 at 17:48

1 Answers1

0

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.

jiku
  • 283
  • 5
  • 16