开发者

Using form in multiple locations -- controller should redirect to different location depending on where the request came from

I have a form to add a staff member.

The form is first used when an account is created in a sequence of view to help the user setup their account.

It is then used 开发者_StackOverflowin a different place once the account has already been setup.

These two use different layouts and controllers, so have different URLs. However, when the form is submitted, they both currently call the same controller#create. Now, if the form is submitted form the setup area, it should redirect to one URL after the create action is called. It should go to a different location if it's called from the main application UI (non-setup).

What's the simplest way to set this up?


The general consensus is to implement a method that stores the url you'd like to return to in the session. For example, store the url in session[:return_to] and in your controller's action use redirect_to session[:return_to].

Obviously I'm simplifying this and you'd want something more robust, wrapped in, say, a before filter that abstracts the management of session[:return_to]. See these SO posts for ideas:

Redirecting from an update action to the referrer of the edit

Correctly doing redirect_to :back in Ruby on Rails when referrer is not available

Alternatively, one lightweight approach is to simply add the target url for the redirect as a hidden form parameter, eg hidden_field 'redirect_to', :value => foo_path (my syntax may not be right). Your reused action would merely redirect_to params[:redirect_to].

I was thinking about this on the way to work and there's got to be a gem, or some better "declarative" way to approach controller action redirects/renders that complements reuse. I just can't think of any existing gems off the top of my head. Time to create?


the :back symbol is the simple answer: redirect_to :back

More depth discussed here: Correctly doing redirect_to :back in Ruby on Rails when referrer is not available

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜