Corban Brook
Corban Brook

Reputation: 21378

Showing error messages in a redirected request

I am using Authlogic to do some simple signup and login stuff. In my WelcomeController I want to have the signup and login forms on the same page 'index' with form actions set to their individual controllers, UsersController and UserSessionsController, respectively. These controllers redirect the user to the protected profile page within the site on successful signup/login. On error I need to redirect back to the WelcomeController#index and display their errors. Upon doing a redirect this information is lost and I cannot use a render because it is a different controller. What is the correct way to handle this behavior?

I could perhaps store the error messages in the Flash Hash. This seems like the easiest solution.

Lately I have stumbled across this problem in another application I was writing where I needed to render summary pages from researcher submitted RFP forms from a PeerReviewerController. Seemed like in that case the use of now deprecated components would have been the right way to handle this. ie: render_component :controller => 'RFPForms', :action => 'summary', :id => 213

Components seem like the DRY way to do something like this. Now that we don't have them what is the correct solution?

Upvotes: 1

Views: 857

Answers (3)

Adam Spiers
Adam Spiers

Reputation: 17916

Drew's answer does not cater for more complex error data (e.g. an array of validation errors), and Marten's answer would risk violating the DRY rule by needing to duplicate code from WelcomeController#index.

A better-looking answer (which is an elaboration on the original poster's idea of storing error data in the flash) is available in Rails validation over redirect although unfortunately I am still personally struggling to get it working ...

Upvotes: 0

Marten Veldthuis
Marten Veldthuis

Reputation: 1910

You could do a render:

render :template => "welcome/index"

But you'd have to make sure that any variables that page expects are loaded, or it won't render.

Upvotes: 1

Drew Blas
Drew Blas

Reputation: 3028

One simple and easy way to do this is to pass a parameter on the redirect:

redirect_to welcome_url(:login_error=>true)

In your view or controller you can then test for that param:

<% if params[:error] -%>
  <div class="error">My Error Message</div>
<% end -%>

Upvotes: 1

Related Questions