Short version of my question
In Rails ActiveRecord, if I have a Boolean field and I assign it something like "abc
" or 2
, then it gets immediately cast to false
. The value 1
is cast to true
, and nil
remains as nil
. Why is this the case? Where can I find Rails documentation (or Ruby documentation) that explains this behavior?
Long version of my question
I am having difficulty understanding how Rails handles attempts to assign values to a Boolean
field in a Rails model. For example, let's say I have a Website
model that has a String
field called :domain
and a Boolean
field called :can_ssl
.
My migration looks like this:
class CreateWebsites < ActiveRecord::Migration
def change
create_table :websites do |t|
t.string :domain
t.boolean :can_ssl, :default => false
t.timestamps
end
end
end
In my model file, I add some validation rules, so it looks like this:
class Website < ActiveRecord::Base
validates :domain, :presence => true
validates :can_ssl, :inclusion => { :in => [true, false] }
end
Simple enough. Based on what I've done, I'm expecting that :can_ssl
can only be set to the values true
or false
, and nothing else. Anything else would result in valid?
being false
.
But once I start playing around in the console, I notice that, as early as the actual assignment statement, the value I provide is being recast to true
or false
(or nil
). What are the rules governing how a value gets cast as a Boolean
?
Examples from the console:
w = Website.new
w.domain = 'stackoverflow.com'
w.can_ssl = true
w.can_ssl # => true
w.valid? # => true
w.can_ssl = nil
w.can_ssl # => nil
w.valid? # => false (so far so good)
w.can_ssl = 'abc'
w.can_ssl # => false (How did 'abc' become the value false?)
w.valid? # => true
w.can_ssl = 1
w.can_ssl # => true (I guess it makes sense that 1 casts to true)
w.valid? # => true
w.can_ssl = 2
w.can_ssl # => false (But anything other than 1 casts to false?)
w.valid? # => true
So, based on what I've done so far, I think I can conclude the following:
- When assigning the value
1
ortrue
to aBoolean
field, the value will immediately get cast astrue
and then assigned. - When assigning
nil
to aBoolean
field, the field is actually assignednil
. - When assigning anything else (such as a
String
or any number that is not1
), then the value will immediately get cast asfalse
.
Am I understanding that correctly? Am I missing anything?
I'm having difficulty finding documentation the Boolean
field type in Rails which can give me clarification on this.