试图让Cancan在一个应用程序中保护几个模型,并好奇它为什么不像我想的那样工作。我原以为您可以在特定实例上使用can?,而不是整个类,所以,在本例中不是这样,但是,您可以在每个实例的基础上在显示一个帖子列表时启用功能?!?
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
if user.role? :admin
can :manage, :all
elsif user.role? :moderator
can :manage, Post
else
can :read, :all
end
end
end
# posts/index.html.haml
...
- if can? :update, @post <- doesn't work
- if can? :update, Post <- works编辑:添加PostsController.rb
#posts_controller.rb
class PostsController < ApplicationController
before_filter :login_required, :except => [:index, :show]
load_and_authorize_resource :except => [:create]
def index
# @posts = Post.all ## <- handled by Cancan's load_and_authorize_resource
@events = Event.where("end_date <= :today", :today => Date.today)
@next_event = Event.next
respond_to do |format|
format.html # index.html.erb
format.json { render json: @posts }
end
end
...
end发布于 2011-08-11 22:38:49
这一行:
- if can? :update, @post <- doesn't work是问CanCan“我能更新这个特定的帖子吗?”你定义了所有职位的能力。如果你做了:
can :update, Post, :user_id => user.id那你的“如果可以吗?”用户将只能更新自己的帖子。因此,如果有关资源实例的内容确定了权限,则希望使用特定的资源版本("@post"),如果用户有能力处理类的所有实例,则希望使用类版本("Post")。
https://stackoverflow.com/questions/7033100
复制相似问题