I have a standard html form post that is being persisted and validated with a rails model on the server side.
For the sake of discussion, lets call this a "car" model.
When
car.save
is invoked the validators fire and set a list of fields in error within the model.
How best can I get an object back that has the fields whose validation failed removed, i.e. such that I don't have to delete the fields on the form the user entered correctly?
The validation patterns they use are great but how do I get a hook to when the validation fails such that I can delete the bogus entries from the model?
I could see manually iterating over the errors list and writing a big case statement but that seems like a hack.
EDIT: Don't do this (see comments) but if you must here is how:
I ended up using a call to
@car.invalid?
inside of a loop to remove the invalid entries:
params[:car].each do | key, array|
if @car.errors.invalid?(key)
@car[key.to_sym] = ''
end
end
render :action=> 'new'
Note the use of the render here vs. redirect. Getting error messages to persist from the rails model validation across a redirect appears tricky, see: Rails validation over redirect
I still feel like there should be a helper method for this or a better way.