想要達到
謝謝觀看。
我正在使用 Rails 進行開發。
我已經在模型上設定了驗證,但是最大字符數的驗證無法正常作業。
公司.rb
validates :price,
length: { maximum: 20 },
presence: true,
numericality: true
像這樣寫,
然后使用表單 輸入20個字符(10000000000000000000)時驗證會跳閘。
順便說一下,19個字符(1000000000000000000)也通過了驗證,18個字符(100000000000000000)通過了驗證。
表單.vue
<template>
<main>
<form>
<fieldset>
<legend>price</legend>
<div class="form-row">
<b-form-input class="form-control" type="text"></b-form-input>
</div>
</fieldset>
</form>
</main>
</template>
模式檔案
create_table "companies", id: :bigint, unsigned: true, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4", force: :cascade do |t|
?
?
?
t.decimal "price", precision: 24, scale: 4
?
?
?
params(當輸入 20 個字符并捕獲驗證時)
Parameters: {"price"=>"10000000000000000000"}
我看引數的時候是字串,所以我在控制器接收引數的地方改了一下,還是驗證失敗。
def create_company_params
params.require(:company).permit(
).tap do |v|
v[:price] = v[:price].to_i
end
end
我不明白為什么驗證中的最大字符數與我在模型中設定的不同。
如果您有任何建議,請讓我知道。
環境
Ruby 2.6 Ruby on Rails 6.0
uj5u.com熱心網友回復:
這是因為您使用的是decimal型別欄位,并且資料庫欄位中存盤了更多字符,這是一個提示
instance.price = 123
instance.price.to_s # => '123.0'
您還指定了 a scaleof 4,這意味著該數字在整數部分后可以有 5 個字符(4 位數字和一個點)。
可能更適合您的用例的不是length,而是less_than_or_equal_to驗證。
https://guides.rubyonrails.org/active_record_validations.html#numericality
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/350226.html
標籤:红宝石轨道
