ruby中布尔类型字段的非空校验

无法用validate_presence_of来对boolean类型字段进行非空校验

migration代码

class CreateCorporateFinancials < ActiveRecord::Migration
  def self.up
    create_table :corporate_financials do |t|
      t.integer :corporate_id
      t.boolean :is_audit, :null => false, :default => false
      t.text :balance_sheet
      t.timestamps
    end
  end

  def self.down
    drop_table :corporate_financials
  end
end

model:

class CorporateFinancial < ActiveRecord::Base
  serialize :balance_sheet, Hash
  belongs_to :corporate
  validates_presence_of :is_audit
end
  corporate_financial = CorporateFinanical.new(params)
  cor_fina = CorporateFinancial.new(params)
  corporate_financial.is_aduit  
  => false
  cor_fina.is_audit
  => true
  corporate_financial.valid?
  => false
  corporate_financial.errors
  => {:is_audit => "不能为空"}

  cor_fina.valid?
  => true

当is_audit的值为false的时候,rails认为其值为空,意味着在对布尔类型的字段进行非空校验时不能用validates_presence_of,我的解决方法是: validates_inclusion_of :is_audit, :in => [true, false]

你可能感兴趣的:(ruby)