1

私はredirect_toがどのように機能するか混乱しています...以下のコードには、何があってもリダイレクトするauthorizeメソッドがあります(私の質問の例として、これは私のアプリケーションにifステートメントがあります)。次に、UsersController で、authorize メソッドを拡張し、その下にいくつかのロジックを追加します。

username「 nil:NilClass の未定義メソッド」というエラーが表示されます。(まあ、 current_user は定義されていませんが、このステートメントの前にリダイレクトが必要です)

私の質問は、「スーパー」への呼び出しが何があってもリダイレクトする必要があるときに、UsersController 承認メソッドのコードが実行され、そのコードが実行されるべきではないのはなぜですか?

class ApplicationController < ActionController::Base
  before_filter :authorize

  def authorize
    redirect_to root_path, alert: 'Not authorized'
    return false
  end

  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end
end

class UsersController < ApplicationController

  def authorize
    super
    return true if current_user.username == 'admin'
  end
end
4

1 に答える 1

1

redirect_toメソッド呼び出しチェーンを停止しません。コントローラーにリダイレクトヘッダーを送り返すように指示するメソッドを呼び出しているだけです。authorizeメソッドを機能させたい場合はUsersController、次のようにする必要があります。

super && current_user.username == 'admin'

ApplicationControllerまた、のauthorizeメソッドも を返すように変更する必要がありますtrue。が を返し、さらにも返す場合、UsersController のこの新しいコードApplicationControllerもを返します。authorizetruecurrent_user.usernametrueauthorizetrue

于 2013-08-11T21:36:37.330 に答える