4

I a boolean "guessed" on my model "perks" and I am trying to get all customers that have perks where guessed is true.

My first guess was this:

@customer = Customer.includes(:perks).where('perks.guessed = true')

But that gives me an SQL-exception: "no such column: true"

A bit of googling gave me this thread: Rails - how to search based on a boolean field? (MySQL error)

So I tried:

@customer = Customer.includes(:perks).where('perks.guessed = 1')

No luck...

Also tried:

@customer = Customer.includes(:perks).where('perks.guessed LIKE, ?', 'true')

@customer = Customer.includes(:perks).where('perks.guessed = t')

What is the correct way to query for the value of a boolean with a where-statement in activerecord?

I'm using SQLite on dev and Postgres on production btw.

Community
  • 1
  • 1
zkwsk
  • 1,960
  • 4
  • 26
  • 34
  • Try this `@customer = Customer.includes(:perks).where('perks.guessed = ?', true)` – Pavan Jul 22 '14 at 15:05
  • Wuh! That was it! Probably the only combination I had not tried. Post as an answer and I'll accept it. – zkwsk Jul 22 '14 at 15:07

3 Answers3

9

This should work

@customer = Customer.includes(:perks).where('perks.guessed = ?', true)

OR

Looking at one of your query

this @customer = Customer.includes(:perks).where('perks.guessed = t')

should be

@customer = Customer.includes(:perks).where("perks.guessed = 't'")
Pavan
  • 33,316
  • 7
  • 50
  • 76
3

This syntax worked for me in Rails 4.

    @user = User.all.where(:yourboolvar => true)
Wraithseeker
  • 1,884
  • 2
  • 19
  • 34
2

You want to allow Rails to convert any values appropriately into SQL. Everything you've tried attempts to second-guess Rails somehow.

The correct form should be:

@customer = Customer.includes(:perks).where('perks.guessed = ?', true)
Amit Joki
  • 58,320
  • 7
  • 77
  • 95
A Fader Darkly
  • 3,516
  • 1
  • 22
  • 28