我不明白我错过了什么。
ability.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
can :read, Post
end
endpost_controller.rb
class PostController < ApplicationController
before_filter :authenticate_user!
def index
@posts = Post.all
authorize! :read, @posts
end
endindex.html.haml
- if can? :read, @posts
you can!
- else
you cannot!使用这段代码,我总是得到CanCan::AccessDenied in PostController#index异常。上面说#8:authorize! :read, @posts出了点问题
1.如果我像这样更改post_controller.rb中的代码,则为:
post_controller.rb
class PostController < ApplicationController
before_filter :authenticate_user!
load_and_authorize_resource
def index
@posts = Post.all
end
end例外情况已经消失,但我从我的观点中得到了you cannot!。我希望能收到you can!消息。
2.如果我在ability.rb中将can :read, Post更改为can :read, :all,我将得到预期的you can!消息。但这不是我想用的。
这里怎么了?
发布于 2014-03-20 11:04:54
实际上,要么使用can :read, Post,要么在循环@posts时使用can :read, post。
两者之间没有关系。
顺便说一句,如果您使用load_and_authorize_resource,则不需要添加@posts = Post.all。
它们是自动装载的。
PS:为什么你要检查你的控制器和你的看法?
https://stackoverflow.com/questions/22530918
复制相似问题