Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
509 views
in Technique[技术] by (71.8m points)

activerecord - Rails database defaults and model validation for boolean fields

In a Rails model I have an attribute is_subscriber, when I constructed a db migration to add this column to the database I specified the default value to be false:

t.boolean  "is_subscriber",   :default => false

I also specified in the model that this attribute needs to be present:

validates :is_subscriber, presence: true

So why do I get this error when I create a model instance without specifying this attribute?

2012-05-08T21:05:54+00:00 app[web.1]: ActiveRecord::RecordInvalid (Validation failed: Is subscriber can't be blank):
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From here

If you want to validate the presence of a boolean field (where the real values are true and false), you will want to use validates_inclusion_of :field_name, :in => [true, false] This is due to the way Object#blank? handles boolean values. false.blank? # => true

Or in Rails3 way

validates :field, :inclusion => {:in => [true, false]}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...