Rails的数据库布尔值 [英] Rails database boolean values

查看:464
本文介绍了Rails的数据库布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

code第一:

create_table :users do |t|
  ...
  t.boolean :is_active, :default => true
  ...
end

现在,这里是我的问题 - 我创建一个rake任务要导入的记录(10000)大的多。我已经做了广泛的测试和基准,并确定执行此任务的最快和最有效的方法是创建一个巨大的原始的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(", ")}"

一切的伟大工程。整个过程就完成了(直译)秒,而不是1.5小时使用ActiveRecord的。不过,我的问题出在布尔领域。我在当地发展上的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

I believe that you might be looking for ActiveRecord::Base.connection.quoted_true

这将返回本土的报价布尔值,例如: 1为SQL Server或MySQL和PostgreSQL的或SQLite的T

This returns native boolean values in quotes, e.g. '1' for SQL Server or MySQL, and 't' for PostgreSQL or SQLite

这篇关于Rails的数据库布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆