Rails database defaults and model validation for boolean fields

前端 未结 4 1528
野性不改
野性不改 2020-12-03 16:39

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 fal

相关标签:
4条回答
  • 2020-12-03 17:18

    I've solved this with:

    validates_presence_of :is_subscriber, :if => 'is_subscriber.nil?'
    
    0 讨论(0)
  • 2020-12-03 17:20

    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]}
    
    0 讨论(0)
  • 2020-12-03 17:23

    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
    
    0 讨论(0)
  • 2020-12-03 17:23
    validates :column_name, :inclusion => {:in => [true, false]}
    
    0 讨论(0)
提交回复
热议问题