1

So often I have a form in some webpage that the user submits to a POST, PUT or DELETE action in Rails where I want it to redirect to a specified URL if the submission was a success. I typically make a hidden extra parameter called to with a path like /users. So if the form submission failed, it just stays on that form, but if it succeeds then the browser is redirected to /users.

I'd like to automatically look for this parameter and always redirect to it if a form submission succeeded in any controller/action. Do I put this in the ApplicationController within an after_action?

class ApplicationController < ActionController::Base
  after_action :redirect_if_success

  private
  def redirect_if_success
    redirect_to params[:to] if params[:to]
  end
end

I guess I can check the request object if this was a POST, PUT or DELETE action. How do I know the submission was a success? Will a redirect_to in the after_action override any redirect_tos in the form controller?

4

2 に答える 2

0

解決策は、アプリケーションコントローラーでプライベートメソッド redirect_if_success を定義することだと思いますが、アクションで直接呼び出します。例えば:

class ApplicationController < ActionController::Base

  private
  def redirect_if_success(default_ur)
     redirect_to params[:to] || default_url
     # or similar logic
  end
end

class UserController < ApplicationController::Base

  def create
    redirect_if_success("/users") if @user.save
  end
end
于 2013-10-24T16:32:31.083 に答える
0

ヘルパーメソッドを作成します

def redirect_to_location
  redirect_to params[:to] && params[:to].present?
end

この動作が必要な各アクションで明示的に使用します。

ただし、少し実験することはできます。このロジックを after_action に保持するには、リダイレクトが必要かどうかを知らせる状態をセットアップする必要があります。

あなたができる:

def save
  if @user.save
    @follow_redirect = true
  end
end

after_action フィルターで @follow_redirect フラグを確認します。非常にきれいなソリューションのようには見えませんが、うまくいきます。

また、応答変数を調べて、アクションを既にリダイレクトまたはレンダリングしているかどうかを確認することもできます (動作するかどうかはわかりませんが、実験するのは楽しいです)。

したがって、次のことを確認できます。

リダイレクトする必要があり (アクションは post/put/delete)、params[:to] が存在し、まだリダイレクト/リダイレクトされていない場合

# this is not a copy-paste code but rather to demonstrate an idea
class ApplicationController < ActionController::Base 
  after_action :redirect_to_location

  protected 

  def is_redirectable?
    %w{post put delete}.include?(request.method) && params[:to].present?
  end

  def already_redirected?
    !response.status.nil? # not sure if it would work at all 
  end

  def redirect_to_location
     redirect_to params[:to] if is_redirectable? && !already_redirected?
  end
end
于 2013-10-24T16:55:24.863 に答える