我试图在 SQLite3 表中插入一个假 bool 值,但它总是插入一个真值。
这是我的迁移:
class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.column :name, :string
t.column :active, :boolean, :default => false, :null => false
end
end
def self.down
drop_table :resources
end
end
当我尝试使用 rails 插入时,它会生成以下 SQL:
INSERT INTO "users" ("name", "active") VALUES ('test', 'f')
SQLite 将“f”视为 true,因此它将 true 插入到我的数据库中。我希望它生成的查询是:
INSERT INTO "users" ("name", "active") VALUES ('test', false)
我做错了什么?
rails :3.0.7
sqlite3 gem :1.3.3
最佳答案
SQLite 使用 1 for true and 0 for false :
SQLite does not have a separate Boolean storage class. Instead, Boolean values are stored as integers 0 (false) and 1 (true).
但 SQLite 也有一个松散的类型系统并自动转换东西,所以你的 'f'
可能被解释为具有“真”的真实性,仅仅是因为它不是零。
稍加挖掘表明您在 Rails 3.0.7 SQLiteAdapter 中发现了一个错误。在 active_record/connection_adapters/abstract/quoting.rb
中,我们找到这些:
def quoted_true
"'t'"
end
def quoted_false
"'f'"
end
因此,默认情况下,ActiveRecord 假定数据库理解 bool 列的't'
和'f'
。 MySQL 适配器覆盖这些以使用 bool 列的 tinyint
实现:
QUOTED_TRUE, QUOTED_FALSE = '1'.freeze, '0'.freeze
#...
def quoted_true
QUOTED_TRUE
end
def quoted_false
QUOTED_FALSE
end
但 SQLite 适配器不提供其自己的 quoted_true
或 quoted_false
实现,因此它获得不适用于 SQLite bool 值的默认值。
''
和 'f'
bool 值在 PostgreSQL 中工作,所以也许每个人都在使用 PostgreSQL 和 Rails 3,或者他们只是没有注意到他们的查询是'无法正常工作。
我对此感到有点惊讶,希望有人能指出我哪里出错了,你不可能是第一个在带有 Rails 3 的 SQLite 中使用 bool 列的人。
尝试猴子修补 def quoted_true;'1';end
和 def quoted_false;'0';end
到 ActiveRecord::ConnectionAdapters::SQLiteAdapter
(或暂时将它们手动编辑到 active_record/connection_adapters/sqlite_adapter.rb
)并查看您是否获得了合理的 SQL。
关于ruby-on-rails - Rails 3 SQLite3 bool 值 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6013121/