Want to achieve
Thanks for watching.
I'm developing using Rails.
I have set up validates on model, but the validation of the maximum number of characters does not work properly.
company.rb
validates :price,
length: { maximum: 20 },
presence: true,
numericality: true
Write it like this,
and then use the form The validation will be tripped when 20 characters (10000000000000000000) are entered.
By the way, 19 characters (1000000000000000000) also tripped the validation, and 18 characters (100000000000000000) passed the validation.
Form.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>
schema.rb
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 (when 20 characters are entered and the validation is caught)
Parameters: {"price"=>"10000000000000000000"}
When I looked at the parameters, they were strings, so I changed in the place where the controller receives the parameters, but it still failed to validate.
def create_company_params
params.require(:company).permit(
).tap do |v|
v[:price] = v[:price].to_i
end
end
I don't understand why the maximum number of characters in the validation is different from what I set in the model.
If you have any suggestions, please let me know.
Environment
Ruby 2.6 Ruby on Rails 6.0
CodePudding user response:
This is because you're using a decimal
type field and more chars are stored in the database field, here's a hint
instance.price = 123
instance.price.to_s # => '123.0'
You also specified a scale
of 4, that means that the number could have 5 characters after the integer part (4 digits and one dot).
Possibly what will fit your use case better is not length
, but less_than_or_equal_to
validation.
https://guides.rubyonrails.org/active_record_validations.html#numericality