Misha Moroshko
Misha Moroshko

Reputation: 171479

How to prevent Rails from changing the content of the input field when validation fails?

I have a decimal price field in my product model, and a simple validation:

class Price < ActiveRecord::Base
  ...
  validates_numericality_of :price
  ...
end

If I type by mistake 33.0p, it says: "Price is not a number" (I agree), and changes the content of the input field from 33.0p to 33.0.

So, if I type 33.0p and press the submit button quickly (thinking that everything is OK), I will get the error message. Then I will look into the input field to check what's wrong. But, there I will see a valid number (33.0), and I will ask myself "What's wrong...?".

Is there any way to prevent Rails from changing the input field content when validation fails ?

Upvotes: 1

Views: 407

Answers (2)

encoded
encoded

Reputation: 1174

Another option would be to use read_attribute_before_type_cast, ie f.text_field(:price, :value => @product.read_attribute_before_type_cast(:price)).

Upvotes: 2

vonconrad
vonconrad

Reputation: 25387

The reason for this is the same as my answer to your other question; Rails converts the input to a float at some point during the process, and therefore the float value is what shows up.

I haven't tested this, but you can try overriding the value of the text field to be params[:product][:price]. In theory, this would look something like:

f.text_field(:price, :value => (params[:product] ? params[:product][:price] : @product.price))

Upvotes: 1

Related Questions