Rails 4.x how to query boolean value with activere

2019-07-05 03:13发布

问题:

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.

回答1:

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'")


回答2:

This syntax worked for me in Rails 4.

    @user = User.all.where(:yourboolvar => true)


回答3:

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)