Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying attributes before type casting upon model validation failure

I have a form where the user can enter a number. The user should only enter whole numbers into the form and there is a model-level validation to check that. The data, of course, come in as a string in the params and are cast to the correct data type (int) by Rails.

If the user enters incorrect data into the particular form field, like a letter or decimal, the validations do not pass and the form is re-rendered. When the user is taken back to the form, however, the inputted data are not shown -- the cast data appear in the field. Is there any way to display the attributes before type casting back in the form upon validation failure?

like image 766
Diana E Avatar asked Jul 10 '26 06:07

Diana E


1 Answers

There is a _before_type_cast helper in rails

You can use it like this:

u = User.first
u.phone
u.phone_before_type_cast

Alternatively in your form, you can populate the field with the value in params if its there.

Will help you more if you post the form code snippet

like image 112
Ruslan Avatar answered Jul 11 '26 20:07

Ruslan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!