I have a create action for a form that potentially generates errors (i.e. first name is missing) and then redirects.
The problem is, that when the redirect happens those form errors get lost. How could I pass those form errors in a session to be displayed back in the original form (which should still be filled out with the previous details, as in the original error_messages behavior)?
Thanks!
The code:
def create
@contact = Contact.new(params[:contact])
if @contact.save
flash[:notice] = "Sent."
else
flash[:notice] = "Error."
end
end
This is a tricky problem that I've had trouble with myself. The first question I would ask is why do you need to redirect when errors are found? Forcing you to render the action when there are errors was a conscious decision of the designers of the Rails framework due to complexity and usability concerns.
Here's the big issue, so in your action, you create an instance of a model using params, the object validation fails and you decide to redirect to another action. Before redirecting to another action you would have to save the current state of your model instance to the session and then redirect to action :foo. In action :foo you'd have to reattempt to update the attributes and pass the errors to the view via an instance variable. The issue here is that you're coupling actions in your controller which is a bad thing (one action is dependent on the other). There are a host of other problems which I could type about forever, but if you only need to do this for one resource, here's how I'd do it:
config/routes.rb
map.resources :things, :member => { :create_with_errors => :get }
things_controller.rb
def new
@thing = Thing.new
end
def create
@thing = Thing.create(params[:thing])
if @thing.save
redirect_to things_path
else
session[:thing] = @thing
redirect_to create_errors_thing_path(@thing)
end
end
def create_with_errors
@thing = session[:thing]
@errors = @thing.errors
render :action => :new
end
app/views/things/new.html.erb
<% if defined?(@errors) %>
<% #do something with @errors to display the errors %>
<% end %>
<!-- render the form stuff -->
I know what you're thinking... this is hideous. Trust me, I've made lots of attempts to address this problem and I've come to realize, the mechanism the rails developers have chosen is the best and easiest way to deal with errors.