2013-10-19 39 views
0

我想創建一個輔助的方法來檢查,如果用戶被授權使用某些功能,如newcreateeditupdatedestroy記錄爲零。實例變量公共控制器方法

當它進入視圖時,它會生效,但我想阻止聰明的用戶通過輸入正確的URL來創建新的Games

在我的控制,我有:

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

def destroy 
    if [email protected] 
    @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是空...

我懷疑這是因爲實例變量是在私有空間中聲明的,但是如果它可用於視圖,爲什麼它不可用於控制器...

不管怎樣,任何人都有任何建議,或正確的方法做我自己的事試圖做,這將不勝感激。

謝謝。

+0

是什麼讓你認爲'@ admin'被分配一個非nil值爲'is_admin'? –

回答

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 
0

由於current_user已被緩存,因此沒有意義緩存@admin。或者,如果current_user未被緩存,則不需要緩存admin。

根據目前的代碼,一個簡單的檢查角色的方法是將其設置模型級別

class User < ActiveRecord::Base 
    def admin? 
    role.match /admin/i 
    end 
end 

然後在控制器

def destroy 
    if current_user.admin? 
    # other code 
    end 
    # other code 
end 
+0

這看起來好像是一個更好的方法來處理它,謝謝。但是,我在哪裏可以找到'match'方法的文檔。 – SnareChops

+0

@SnareChops,如果你只想使用它一次並區分管理員,那麼方法就沒有問題了,對於更多規則,最好檢查CanCan。對於匹配文檔,在這裏你是:http://apidock.com/ruby/String/match –

+0

我剛剛注意到你的角色不是用戶表中的字段,而是另一個字段,因此特定的代碼需要根據你的設置進行更改。無論如何,原則是一樣的,這樣的工作應該在模型層面完成。 –

相關問題