6

NameError (undefined local variable or method "current_user" for #<APIRouter:0x007ffd54a81f98>):マッチで current_user を使用しようとするとエラーが発生しますか? 制約。特定のダミー ユーザーを 1 つのコントローラー セットにルーティングし、他のユーザーを別のコントローラー セットにルーティングしたいと考えています。ただし、 current_user を使用しようとすると、エラーが発生します。

  • 考案 (2.0.4)
  • レール (3.2.2)

私の一致制約は APIRouter クラスで定義されています。

class APIRouter
  def matches? request
    @use_rm_app = ENV["USE_RM_APP"] == "true" || (current_user && current_user.is_test)
  end
end

試合で現在のユーザーをどのように使用できるかについてのアイデアはありますか? Rails ガイドで定義されている制約。

routes.rb ファイルのセクション:

#  Route to the rm_app controller if APIRouter says we should, otherwise use the real backend controllers.
match '/api/v1/*path', :controller => 'api/v1', 
  :action => 'handle_create_request', 
  :via => :post, :constraints => APIRouter.new

更新: ksol のおかげで解決しました。 3作品挑戦。使用してユーザーを取得request.env["warden"].user(:user)

解決策は、APIRouter を変更することです

  def matches? request
    user = request.env["warden"].user(:user)
    (user && user.is_test) || ENV["USE_RM_APP"] == "true"
  end
4

3 に答える 3

15

current_userコントローラとビューでのみ使用できます。目的を達成する方法は複数あります。メソッドにパラメーターとして指定する方が簡単です。

編集

ルーターでアクセスできる場合current_userは、を実行して制約クラスに渡すことができますconstraints: APIRouter.new(current_user)APIRouter#initialize次に、で使用できるインスタンス変数にcurrent_userを定義して保存する必要がありますmatches?

編集2

deviseを使用すると、ルーターでこれを実行できることを思い出しました。

authenticated :user do
  root :to => "main#dashboard"
end

それを確実にする方法はわかりませんuser.is_testが。

編集3

最後の試行。request.env["warden"].user(:user)1つが認証されている場合は、ユーザーを提供する必要があります。

于 2012-09-25T18:38:23.873 に答える
6

ksol の投稿に基づいて、認証済みにブロックを渡すことで user.is_test を確認できます。

authenticated :user, lambda {|u| u.is_test } do
    // route stuff here
end

これは、u.is_test がブール値を返すことを前提としています。

于 2013-10-04T03:37:28.550 に答える
0

両方のルートについて diff :as を追加することを忘れないでください。そうしないと、エラーが発生します

authenticated :user do
  root :to => "main#dashboard", :as => :foo
end

root :to => "main#landing_page"
于 2015-06-01T05:35:33.410 に答える