Search code examples
validationruby-on-rails-3formtasticrefinerycms

Form validation errors in Rails 3


I have a form I built using Formtastic in Rails 3. The form submits to the #create action of ClientsController, and if the save is successful the controller redirects to a "thank you" page. If the save is not successful, it redirects to the page where the form is embedded. I'd like to be able to show the validation errors inline on the form page, but after the redirect back to that page, the errors object comes back empty.

What can I do so I can display the validation errors on the form?

Here is the code from the controller.

if client.save && event.save
  redirect_to "/thank-you"
else
  redirect_to :back
end  

Some additional details: I am using RefineryCMS so there is no view for the page where the form is, and therefore I can't render the view.


Solution

  • You need to save your errors into session.

    
    if client.save && event.save
      session[:client_create_errors] = nil
      redirect_to "/thank-you"
    else
      session[:client_create_errors] = client.errors
      redirect_to :back
    end
    

    now you can access errors object from anywere using session[:client_create_errors]