我的问题的简短版本
在 Rails ActiveRecord 中,如果我有一个布尔字段并且我给它分配类似“abc
" or 2
,然后它立即转换为false
。价值1
被投射到true
, and nil
仍然是nil
。为什么会这样呢?在哪里可以找到解释此行为的 Rails 文档(或 Ruby 文档)?
我的问题的长版本
我很难理解 Rails 如何处理为 a 赋值的尝试Boolean
Rails 模型中的字段。例如,假设我有一个Website
模型有一个String
字段称为:domain
and a Boolean
字段称为:can_ssl
.
我的迁移看起来像这样:
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
在我的模型文件中,我添加了一些验证规则,因此它看起来像这样:
class Website < ActiveRecord::Base
validates :domain, :presence => true
validates :can_ssl, :inclusion => { :in => [true, false] }
end
够简单的。根据我所做的事情,我期待 that :can_ssl
只能设置为值true
or false
,没有别的。其他任何事情都会导致valid?
being false
.
但是,一旦我开始在控制台中玩耍,我注意到,早在实际的赋值语句中,我提供的值就被重新转换为true
or false
(or nil
)。控制值如何转换为 a 的规则是什么Boolean
?
来自控制台的示例:
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
所以,根据我迄今为止所做的事情,我think我可以得出以下结论:
- 赋值时
1
or true
to a Boolean
字段,该值将立即被转换为true
然后分配。
- 分配时
nil
to a Boolean
field,该字段实际被赋值nil
.
- 当分配其他任何东西时(例如
String
或任何不是的数字1
),那么该值将立即被转换为false
.
我的理解正确吗?我错过了什么吗?
我很难找到文档Boolean
Rails 中的字段类型可以让我对此进行澄清。