开发者

About Query methods Conditions in Rails 3

开发者 https://www.devze.com 2023-01-28 07:30 出处:网络
Hash way开发者_如何学编程 works just fine: drummers = Drummer.where(:gender => true) => [#<Drummer id: 1, first_name: \"Bernard\", middle_name: nil, second_name: \"Purdie\", nick_name: \"Pr

Hash way开发者_如何学编程 works just fine:

drummers = Drummer.where(:gender => true)

=> [#<Drummer id: 1, first_name: "Bernard", middle_name: nil, second_name: "Purdie", nick_name: "Pretty Purdie", gender: true, created_at: "2010-12-05 02:47:56", updated_at: "2010-12-05 02:50:42">]

But the same thing in String way:

drummers = Drummer.where("gender = true")

I got below error: ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: TRUE: SELECT "drummers".* FROM "drummers" WHERE (gender = TRUE)

anybody could tell mewhy?


This is a sqlite error, not rails. When you say gender = true, it's looking for a column that is named true. Sqlite does not have booleans, so the correct way to do this is Drummer.where("gender = 1").


You should avoid using strings where possible in your Arel queries.

If you're joining a table that also contains a field named 'gender' then this will break, because it's ambiguous. Using where(:gender => true) will automatically be namespaced for you, so that won't happen.

As your example shows, using strings also can create portability problems, if you're using a feature that your backend doesn't support.

I've been using a plugin called MetaWhere to augment ARel's syntax, making strings less necessary.

0

精彩评论

暂无评论...
验证码 换一张
取 消