我的問題是絕對理論的,就像「這是正確的事情嗎?」。 我是Rails的新手,尤其是Ruby,我試圖在我的Rails應用中使用Cancan自動化解決方案。坎康能力定義:整個控制器作爲一個對象
讓我們考慮一下這樣一個簡單的控制器,一對關聯的視圖和一個帶有DB表的用戶模型。
class UsersController < ApplicationController
def index
@users = User.all
end
def show
@user = User.find(params[:id])
end
end
的目標是限制訪問「指數」的方法,但所有管理員和允許普通用戶只能看到他們自己的網頁,例如允許id = 5的用戶看到「users/5」頁面。 對於這個範圍,我已經爲康康創建了一個能力類。那就是:
class Ability
include CanCan::Ability
def initialize user, options = {}
default_rules
if user
admin_rules(user) if user.role.eql? "admin"
player_rules(user) if user.role.eql? "player"
end
end
def admin_rules user
can :read, UsersController
end
def player_rules user
can :read, User do |user_requested|
user_requested.id == user.id
end
end
def default_rules
end
end
我的問題是: 我應該使用UsersController如「可以」方法的對象,如果我沒有類型用戶的方便嗎?稍後在控制器的「索引」方法中使用「authorize!:show,UsersController」。或者它應該以其他方式完成? 謝謝你的建議。
謝謝,這很有用。 – user1261595