Rails - how to search based on a boolean field? (MySQL error)

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-12 10:32:33

问题


I'm running the following query

@projects = @company.projects.where("active = ?", true).order("created_at ASC")

and I'm getting the error:

`ActiveRecord::StatementInvalid: Mysql::ParseError: You have an error in your SQL...`

the error points to the = '1'.

I've tried many variations on my query but I cannot figure out the problem. How can I solve this?


回答1:


You don't need to use parameterized queries with literals, just do this:

@projects = @company.projects.where("active = 1").order("created_at ASC")



回答2:


Try:

@projects = @company.projects.where(:active =>  true)

(it also works with strings 'active').

You can also look at http://guides.rubyonrails.org/active_record_querying.html#hash-conditions for more details.

There is also a nice railscast about this which explains why you might have problems (I'm not allowed to post 2 links so you should search for it :) )



来源:https://stackoverflow.com/questions/5015340/rails-how-to-search-based-on-a-boolean-field-mysql-error

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