ruby-on-rails - Rails 3 SQLite3 bool 值 false

标签 ruby-on-rails ruby-on-rails-3 sqlite rails-activerecord

我试图在 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_truequoted_false 实现,因此它获得不适用于 SQLite bool 值的默认值。

'''f' bool 值在 PostgreSQL 中工作,所以也许每个人都在使用 PostgreSQL 和 Rails 3,或者他们只是没有注意到他们的查询是'无法正常工作。

我对此感到有点惊讶,希望有人能指出我哪里出错了,你不可能是第一个在带有 Rails 3 的 SQLite 中使用 bool 列的人。

尝试猴子修补 def quoted_true;'1';enddef quoted_false;'0';endActiveRecord::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/

相关文章:

android - 学生×团体关联的稳定婚姻算法

sql - 更新两列排序的累积总和

mysql - 部署到 Heroku 错误。提供日志

ruby-on-rails - 在 Rails 中生成 slugs(人类可读的 ID)的最佳方法

ruby-on-rails-3 - 如何正确使用Factory_girl和has_many 'through'模型

python - 如何使用 SQL 参数

jquery - 使用 jquery 和 Rails 加载部分内容

ruby-on-rails - 在heroku设置的30秒限制后,大文件上传到亚马逊s3失败

ruby-on-rails - 如何让我的 Ruby Gems 在多个服务器上保持相同?

ruby-on-rails - rails - 如何在 View 中呈现 JSON 对象