Using Rails v2.1, lets say you have an action for a controller that is accessible from more than one location. For example, within the Rails app, you have a link to edit a user from two different views, one on the users index view, and another from another view (lets say from the nav bar on every page).
I'm wondering what is the best way to redirect the user back to the right spot depending on what link they clicked on. For example:
Example 1:
Example 2:
I've seen it done in the past by:
What I don't particularly like about this solution is the need to add the parameter to every applicable link in the views. I'm wondering if there's a way to build this all into the controller.
One better way I was thinking was to:
Any thoughts on the best way to do this?
Flash: Data which you'll use only for the next request can be stored in the flash. Then you don't have to go about automatically clearing it. It works well for limited bits of application context which you're sure to only need once -- not just for error messages!
I know what you did last HTTP access: If you just need to redirect people to the last URL they were at, then just do that. request.referer will, for most browers which don't block the information, give you the last URL the person was at.
#in edit controller
...
flash[:page_to_redirect_to] = request.referer || "/my/default/path"
...
#in save controller
redirect_to flash[:page_to_redirect_to] || "/my/default/path"
I wouldn't suggest hardcoding those, incidentally.
before_filter: I see a lot of Rails developers using this as their favorite hammer and turning everything else into nails. Filters are useful when you want to expose functionality to all or substantially all methods in a controller. I don't know that is necessarily the case here, but your mileage may vary. You can combine the filter with the above two tricks if warranted.
I think that using before_filter on the edit action is the least obtrusive.
The referer should be reliable enough ... simply have a default in the case of no referer being available (say: someone bookmarked the edit page) and you should be fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With