Rails 4.x how to query boolean value with activerecord?

梦想与她 提交于 2019-12-10 17:52:48

问题


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)


来源:https://stackoverflow.com/questions/24890786/rails-4-x-how-to-query-boolean-value-with-activerecord

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!