Pregunta

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.

¿Fue útil?

Solución 2

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.

Otros consejos

In your controller, render the new action from your create action if validation fails, with an instance variable, @car populated from the user input (i.e., the params hash). Then, in your view, add a logic check (either an if block around the form or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car is set.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top