Rails 数据库布尔值
代码优先:
create_table :users do |t|
...
t.boolean :is_active, :default => true
...
end
现在,这是我的问题 - 我正在创建一个 rake 任务来导入大量记录(超过 10,000 条).我进行了广泛的测试和基准测试,并确定执行此任务的最快和最有效的方法是创建一个巨大的原始 SQL 语句.(我正在从 CSV 读取数据).举个例子:
Now, here is my issue - I am creating a rake task to import a LARGE number of records (10,000+). I've done extensive testing and benchmarking and determined that the fastest and most efficient way to perform this task is to create one giant raw SQL statement. (I'm reading data from CSV). As an example:
inserts = Array.new
FasterCSV.foreach(...) do |row|
inserts.push "(row[0], row[1]...)"
end
User.connection.execute "INSERT INTO users (...) VALUES #{inserts.join(", ")}"
一切都很好.整个过程在(字面上)几秒钟内完成,而不是使用 ActiveRecord 的 1.5 小时.但是,我的问题在于布尔字段.我在 SQLite 上本地开发,但在生产上使用 MySQL.使用 ActiveRecord 时,Rails 确定在布尔"字段中放入什么(因为几乎所有数据库都不同).我正在编写自定义 SQL,我想知道是否有办法可以执行类似...
Everything works great. The entire process completes in (literally) seconds instead of the 1.5 hours using ActiveRecord. However, my problem lies with the boolean field. I develop locally on SQLite, but MySQL on production. When using ActiveRecord, Rails determines what to put in the "boolean" field (since almost all databases are different). I'm writing custom SQL and I want to know if there is a way I can do something like...
INSERT INTO users(..., is_active, ...) VALUES (..., ActiveRecord::Base.connection.boolean.true, ...)
...正确返回特定于数据库的布尔值.
...that correctly returns the database-specific boolean value.
回答仅使用 ActiveRecord"的任何人都将被否决.在这种情况下根本不可行.我也不愿意使用 tinyint(1) 字段并使用 1 或 0.
Anyone who answers "just using ActiveRecord" will be down-voted. It's simply NOT feasible in this situation. I'm also not willing to use a tinyint(1) field and use 1's or 0's.
综上所述,is_active
的值需要根据当前的数据库连接来改变...
In summary, the value for is_active
needs to change based on the current database connection...
这可能吗?
推荐答案
相信你可能在找ActiveRecord::Base.connection.quoted_true
这将返回带引号的本机布尔值,例如'1' 用于 SQL Server 或 MySQL,'t' 用于 PostgreSQL 或 SQLite
This returns native boolean values in quotes, e.g. '1' for SQL Server or MySQL, and 't' for PostgreSQL or SQLite
相关文章