Reputation: 1131
I need help with error validations/redirects....
If I use format.html {redirect_to :back, flash: {error: "Oops, something went wrong. Please try again."}
the error message works, but it does not hold the form data so the user needs to re-input and doesn't know which fields were incorrect.
The format.xml {render :xml => @award.errors, :status => :unprocessable_entity}
line redirects to back, but it doesn't show any errors.
I would like to see which fields are incorrect, with their validation messages intact. Please help with syntax. Thanks in advance!
respond_to do |format|
if @award.save
format.html { redirect_to(new_award_path, :notice => 'Thank you for your nomination!') }
format.xml { render :xml => @award, :status => :created, :location => @award }
else
format.html {redirect_to :back}
#format.html {redirect_to :back, flash: {error: "Oops, something went wrong. Please try again."}}
format.xml {render :xml => @award.errors, :status => :unprocessable_entity}
end
end
UPDATE to include more detail:
I'm using 2 different forms for this create method. Each form has a hidden field to set a boolean value, then I do stuff in my controller based on that hidden condition. If there are errors, I need to redirect to the correct form, hold its values, and show the appropriate error fields. Something like this:
respond_to do |format|
if @award.save
format.html { redirect_to(new_award_path, :notice => 'Thank you for your nomination!') }
format.xml { render :xml => @award, :status => :created, :location => @award }
else
if boolean_field == true
format.html { render action: "true_form" }
format.xml {render :xml => @award.errors, :status => :unprocessable_entity}
else
format.html { render action: "false_form" }
format.xml {render :xml => @award.errors, :status => :unprocessable_entity}
end
end
end
When I try it this way, errors work, but it always goes back to the true_form, even if I started on the false_form. So, it's like it's ignoring the boolean_field condition... make sense?
Upvotes: 0
Views: 1718
Reputation: 6274
The trick is not redirecting when there are errors, but simply rendering the view again.
respond_to do |format|
if @award.save
format.html { redirect_to(new_award_path, notice: 'Thank you for your nomination!') }
format.xml { render xml: @award, status: :created, location: @award }
else
format.html { render action: 'new' }
format.xml { render json: @award.errors, status: :unprocessable_entity }
end
end
Upvotes: 2