带有 sqlite 的 rails 中的布尔值

2022-01-02 00:00:00 model boolean ruby-on-rails ruby sqlite

我对 Rails 还是个菜鸟,但我遇到了一些看起来有点奇怪的东西.我因此向数据库中的模型添加了一个布尔字段

I am a bit of a noob still with rails, but I am running across something that seems a bit odd. I added a boolean field to a model in the database thusly

t.column :admin, :bool, :default => false, :null => false

然而,sqlite3 数据库中的值似乎不是't''f'.这很好,但如果值为 'f',我仍然希望 user.admin? 返回 false.正如您从以下控制台会话中看到的,情况并非如此:

However, the value in the sqlite3 database seems to be either 't' or 'f'. That is fine, but I would still expect user.admin? to return false if the value is 'f'. As you can see from the following console session, that's not the case:

>> user = User.first
=> #<User id: 2, login: "matt", name: "", email: "google.ninja@no-spam.com", crypt
ed_password: "c6740f820b4cbf6e3d88188719f23cd3053a54f0", salt: "5629f5ee09f51543
a7d64dd903b8d9e53aa43a24", created_at: "2009-04-26 23:08:05", updated_at: "2009-
04-26 23:10:38", remember_token: nil, remember_token_expires_at: nil, admin: "t"
>
>> user.admin?
=> true
>> user.admin = false
=> false
>> user.save
=> true
>> user = User.first
=> #<User id: 2, login: "matt", name: "", email: "google.ninja@no-spam.com", crypt
ed_password: "c6740f820b4cbf6e3d88188719f23cd3053a54f0", salt: "5629f5ee09f51543
a7d64dd903b8d9e53aa43a24", created_at: "2009-04-26 23:08:05", updated_at: "2009-
05-06 03:32:23", remember_token: nil, remember_token_expires_at: nil, admin: "f"
>
>> user.admin?
=> true

这只是 sqlite 的一些奇怪问题,还是我没有得到什么?

Is this just some weird issue with sqlite, or am I just not getting something?

推荐答案

改用这个:

t.column :admin, :boolean, :default => false, :null => false

了解原因 这里.

相关文章