Code first:
create_table :users do |t|
...
t.boolean :is_active, :default => true
...
end
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(", ")}"
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.
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.
In summary, the value for is_active
needs to change based on the current database connection...
Is this even possible?
Yep - it can be null. Your Boolean column is supposed to be only true or false . But now you're in the madness of three-state Booleans: it can be true , false , or NULL .
In Ruby, a boolean refers to a value of either true or false , both of which are defined as their very own data types. Every appearance, or instance, of true in a Ruby program is an instance of TrueClass , while every appearance of false is an instance of FalseClass .
Nullable boolean can be null, or having a value “true” or “false”. Before accessing the value, we should verify if the variable is null or not. This can be done with the classical check : if … else …
I believe that you might be looking for ActiveRecord::Base.connection.quoted_true
This returns native boolean values in quotes, e.g. '1' for SQL Server or MySQL, and 't' for PostgreSQL or SQLite
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With