开发者

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 p开发者_JAVA技巧revent Rails from changing the input field content when validation fails ?


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


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))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜