使用 cancan 时如何设置范围集中分配?
假设我有一个这样的模型“Channel”(课程是一个布尔属性):
class Channel < ActiveRecord::Base
attr_accessible :title
attr_accessible :course, :title, :as => :administrator
end
我正在使用具有以下功能设置的 cancan:
class Ability
include CanCan::Ability
def initialize(user)
if user
if user.administrator
can :manage, Channel
else
can [:read, :create], Channel
can [:update, :destroy], Channel, :course => false
end
end
end
end
这是我当前的控制器设置:
class ChannelsController < ApplicationController
load_and_authorize_resource
###
def new
end
def create
if @channel.save
redirect_to @channel, :notice => "Successfully created channel."
else
render :action => 'new'
end
end
def edit
end
def update
if @channel.update_attributes(params[:channel])
redirect_to @channel, :notice => "Successfully updated channel."
else
render :action => 'edit'
end
end
###
end
我需要在我的中使用 cancan 的 load_and_authorize_resource
方法控制器以防止非管理员用户能够更新课程正确的现有频道,但我还需要使用基于 if/else 的 if/else 中断其资源加载current_user.administrator
设置 :as => :administrator
范围,以便管理员可以访问课程属性。
有没有明智的方法来做到这一点?
Let's say I have a model "Channel" as such (Course is a boolean attribute):
class Channel < ActiveRecord::Base
attr_accessible :title
attr_accessible :course, :title, :as => :administrator
end
I'm using cancan with the following ability setup:
class Ability
include CanCan::Ability
def initialize(user)
if user
if user.administrator
can :manage, Channel
else
can [:read, :create], Channel
can [:update, :destroy], Channel, :course => false
end
end
end
end
Here's my current controller setup:
class ChannelsController < ApplicationController
load_and_authorize_resource
###
def new
end
def create
if @channel.save
redirect_to @channel, :notice => "Successfully created channel."
else
render :action => 'new'
end
end
def edit
end
def update
if @channel.update_attributes(params[:channel])
redirect_to @channel, :notice => "Successfully updated channel."
else
render :action => 'edit'
end
end
###
end
I need cancan's load_and_authorize_resource
method in my controller to prevent non-administrator users from having the ability to update an existing channel where course is true, but I also need to interrupt its resource loading with an if/else based on current_user.administrator
to set the :as => :administrator
scope so administrators have access to the course attribute.
Is there a sensible way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
修复
update
方法非常简单,因为批量分配是由update_attributes
完成的,而不是在load_and_authorize_resource
中完成的:对于
create
如果您最终经常这样做,那么使用简单的自定义过滤器而不是
load_and_authorize_resource
可能是值得的。Fixing the
update
method is pretty straightforward because the mass-assignment is done byupdate_attributes
and not inload_and_authorize_resource
:For the
create
action I think the easiest solution is to do the assignment and the authorization manually:If you end up doing this a lot, it might be worth it to use a simple custom filter instead of
load_and_authorize_resource
.