Rails 3. Leaving wrong value of integer attributes in a form

I have model 'Human' and this model has integer attribute :age. For example, I use validation for this integer attribute :age.

When I add new 'Human' with wrong value of :age (e.g. "2aaa3") it is render me back with error, but it is also cut :age like "2". But I don't want it. I want to leave last wrong value "2aaa3".

So, question is "How can I do it?"


That is the default behaviour of validation in Rails. Not sure if there are any other ways to override it. You could however do that validation using javascript, which will be much more user experience oriented than using validates_numericality_of.

Hi everybody who is interested in my question.

I am glad to say I've created solution by myself. But I have several remarks to that. ))

First, the solution is:

class ApplicationController < ActionController::Base
  after_filter :restore_int_value, :only => [:create, :update]
  def restore_int_value
    response.body = response.body.gsub(/(numeric.*<input id=")([^_]*)(_)([^"]*)(.*value=")(\d+)(")/){$1 + $2 + $3 + $4 + $5 + params[$2][$4] + $7}

Second, remarks are:

1) the solution works along such gems as 'Formtastic' and 'Simple_form'. These gems build the forms wraped in detailed html and give us possibility to use regex. If you don't use such gems you can just wrap all your integer attributes, for example, in 'p' tag with 'numeric' class like following and I think my solution will work for this too:

<p class="numeric"> <%= text_field(:human, :age) %> </p>

2) I think my solution will not work for integer fields of nested models in multiple-models-form. (Ryan Bates describes such kind of work in "Handle Multiple Models in One Form" from "Advanced Rails Recipes"). But if you read Ryan Bates' article you will see that he already uses JavaScript. So, working with nested models in form you need JavaScript. Then you can use JavaScript for validation too (as Kunday told). And you will not have a problem. ;) But if you have static number of nested models in form and do not use JavaScript, then I think you can create new particular regex for your needs (similar to the one I created). I hope you will manage with this. ;)

I hope I've covered all scenarios where you can have such problem and my solution will be useful for somebody, besides me. ;)

Need Your Help

how to auto resize in pyqt4 python?

python python-2.7 pyqt4

I want to auto resize the above picture at the size shown below when user resize the main window. Is there any function to do this in pyqt4? I was searching for an answer to this problem... ...

Sorting a dict on __iter__

python optimization refactoring

I am trying to sort a dict based on its key and return an iterator to the values from within an overridden iter method in a class. Is there a nicer and more efficient way of doing this than creatin...