Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails database boolean values

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?

like image 951
sethvargo Avatar asked Dec 27 '10 22:12

sethvargo


People also ask

Can boolean column be null?

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 .

What is a boolean in Ruby?

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 .

Can a java boolean be null?

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 …


1 Answers

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

like image 163
Scott Avatar answered Oct 17 '22 12:10

Scott