rails4:当数字的比例数超过定义数时,如何呈现错误消息?

时间:2015-11-17 15:39:59

标签: ruby-on-rails-4 rails-activerecord

我想强制用户输入小数点后正好2位数的数字。 目前,当用户键入12.349时,它将自动转换为12.35。相反,应该提出验证错误,如:"请输入小数点后2位数字。"

class Accounting < ActiveRecord::Base

  validates :share_ksk, :central_office, :limit_value, :fix_disagio,
            presence: true, numericality: { less_than: 999.99, greater_than_or_equal_to: 0.00 }
end

我的迁移文件:

class CreateAccountings < ActiveRecord::Migration
  def change
    create_table :accountings do |t|
      t.decimal :share_ksk,         precision: 5, scale: 2, null: false
      t.decimal :central_office,    precision: 5, scale: 2, null: false
      t.decimal :limit_value,       precision: 5, scale: 2, null: false
      t.decimal :fix_disagio,       precision: 5, scale: 2, null: false

      t.timestamps null: false
    end
  end
end

1 个答案:

答案 0 :(得分:1)

您可以使用format验证执行此操作,并为其指定正则表达式:

validates :share_ksk, :central_office, :limit_value, :fix_disagio,
          presence: true, 
          numericality: { less_than: 999.99, greater_than_or_equal_to: 0.00 },
          format: { with: /\d*\.\d{2}$/, message: "must have two digits after decimal point" }

请参阅:http://guides.rubyonrails.org/active_record_validations.html#format