views:

150

answers:

2

I'm currently re-using a partial on two different views.

View A

View B

The partial belongs to Model A but has an association with Model B so it is applicable to Model B as well.

It contains a form and when data is submitted, it always redirects the user to View A. However, when I submit the form from View B, I would like to be redirected back to View B instead of Form A.

The reason it redirects right now to View A is because that's the model this form belongs to. So when posted, it talks to controller A and uses a redirect take the user to a_url.

How can I tell my form (or more so that controller action) to redirect the user back to where they came from?

Thanks!

+2  A: 

Solved.

I added a hidden field to my form that contained the controller name of where the partial was rendered and then my respond_to block determined where to send the user.

View code:

<%= hidden_field_tag 'submitted_from', "#{controller.controller_name}" %>

My controller code:

if params[:submitted_from] == 'A'
  redirect_to a_url
else
  redirect_to b_url
end
mwilliams
A: 

Instead of using a hidden tag, you may want to place this in the session:

session[:submitted_from] = new_model_url

and in the other action..

redirect_to(session[:submitted_from])
session[:submitted_from] = nil

It's pretty easy to switch out form variables, whereas it may be harder (but not impossible) to forge a session. I'd go this route if it were my application.

Josh