Rails database defaults and model validation for boolean fields

孤街浪徒 提交于 2019-11-26 16:59:56

问题


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):

回答1:


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]}



回答2:


I've solved this with:

validates_presence_of :is_subscriber, :if => 'is_subscriber.nil?'



回答3:


I think it is neater to wrap this in a custom validator.

in /app/validators/is_boolean_validator.rb

class IsBooleanValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, parameters)
    if !parameters.in? [true,false]
      record.errors[attribute] << 'This must be true or false.'
    end
  end
end

then you have to make sure this is loaded by adding the following to /config/application.rb

config.autoload_paths += %W["#{config.root}/app/validators/"]

(don't forget to restart your server to load this)

You can then validate more neatly with

validates: :field1, field2, is_boolean: true


来源:https://stackoverflow.com/questions/10506575/rails-database-defaults-and-model-validation-for-boolean-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!