Reputation: 721
I can't understand what I've missed.
ability.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
can :read, Post
end
end
post_controller.rb
class PostController < ApplicationController
before_filter :authenticate_user!
def index
@posts = Post.all
authorize! :read, @posts
end
end
index.html.haml
- if can? :read, @posts
you can!
- else
you cannot!
Using this code, I always get CanCan::AccessDenied in PostController#index
exception. It says there's something wrong at the line #8: authorize! :read, @posts
1.
If I change code in the post_controller.rb
like this:
post_controller.rb
class PostController < ApplicationController
before_filter :authenticate_user!
load_and_authorize_resource
def index
@posts = Post.all
end
end
The exception is gone, but I get you cannot!
from my view. I expect to get you can!
message.
2. If I change can :read, Post
to can :read, :all
in the ability.rb, I get you can!
message as expected. But that's not what I want to use.
What's wrong here?
Upvotes: 0
Views: 41
Reputation: 115511
Actually, either you use can :read, Post
or you use can :read, post
while looping @posts
.
There is no in between.
btw, if you use load_and_authorize_resource
, no need to add @posts = Post.all
.
They are automatically loaded.
PS: why do you check in your controller AND in your view?
Upvotes: 3