0

ログインしたユーザーが、、、、、などの特定の機能を使用する権限を持っているかどうかを確認するヘルパー メソッドを作成しようとnewcreateeditupdateますdestroy

これはビューに到達すると機能しますが、賢いユーザーがGames正しい URL を入力するだけで新しいものを作成できないようにしたいと考えています。

私のコントローラーには次のものがあります:

before_action :is_admin, only: [:index, :platform, :publisher, :new, :edit, :create, :update, :destroy]

def destroy
  if !@admin
    @game.destroy
    respond_to do |format|
      format.html { redirect_to games_url }
      format.json { head :no_content }
    end
  else
    redirect_to @game, notice: 'User not authorized to delete games.'
  end
end

def is_admin
  @admin = current_user.roles.detect {|r| r.name == "Super Admin" || r.name == "Game Admin"}
end

デバッガーを使用すると、プライベート メソッドが実際に呼び出されていることがわかりますが、パブリック メソッド@adminでは null です...

これは、インスタンス変数がプライベート空間で宣言されているためだと思われますが、ビューで使用できる場合、コントローラーで使用できないのはなぜですか...

とにかく、誰かが私がやろうとしていることを行うためのアドバイスや正しい方法を持っていれば、それは大歓迎です.

ありがとうございました。

4

2 に答える 2

0

わかりました、私はより良い方法を考え出しました、そしてそれは今働いています。だから、グーグルからこれに出くわしたすべての人のために、これが私がしたことです...

私の ApplicationController では、いくつかの新しいヘルパー メソッドを作成しました。

class ApplicationController < ActionController::Base

  helper_method :current_user
  helper_method :is_super_admin
  helper_method :is_game_admin

  private

  def current_user
    @current_user ||= Member.find(session[:member_id]) if session[:member_id]
  end

  def is_super_admin
    unless current_user.nil?
      current_user.roles.detect {|r| r.name == "Super Admin"} unless current_user.roles.nil?
    end
  end

  def is_game_admin
    unless current_user.nil?
      current_user.roles.detect {|r| r.name == "Game Admin"} unless current_user.roles.nil?
    end
  end
end

次に、アクセスを制限したいコントローラーで、before_actionこれらの値を取得し、アクションを表示するか、ユーザーをインデックスアクションに戻します...

class GamesController < ApplicationController
  before_action :is_admin, only: [:new, :edit, :create, :update, :destroy]

  #... controller methods

  private

  def is_admin
    unless is_super_admin || is_game_admin
      redirect_to games_url, notice: 'User is not authorized to perform this function.'
    end
  end
end
于 2013-10-19T22:27:28.983 に答える