Reputation: 778
I'm trying to get CanCan set up in a rails app and I'm running into some odd behavior.
My ability.rb
file looks like this:
class Ability
include CanCan::Ability
def initialize(user)
can :create, User
can :create, Template
can :read, :all
end
end
templates_controller.rb
:
class TemplatesController < ApplicationController
load_and_authorize_resource
def index
authorize! :create, Template
end
end
So far, so good. CanCan doesn't complain when I go to /templates
. The weird behavior starts in the view. can?
returns false when asking about :create
and Template
but true when asking for :read
or User
.
views/templates/index.html.erb
:
<% if can? :create, Template %>
Doesn't show up.
<% end %>
<% if can? :read, Template %>
Does show up.
<% end %>
<% if can? :create, User %>
Does show up.
<% end %>
Oh, and here's my template.rb
Model, in case that matters:
class Template < ActiveRecord::Base
attr_accessible :title, :template, :user_id
has_many :radlibs
belongs_to :user
has_reputation :votes, source: :user, aggregated_by: :sum
end
This has got me really stumped, why can I only get at certain permissions in the view, when they work in the controller?
Upvotes: 1
Views: 205
Reputation: 778
So, the problem was 'Template' is also a class in ActionView
. So CanCan was looking at my model in the controller, but was looking at ActionView::Template
in the view, whereas ::Template
was my model, I'm gonna think about changing that.
<% if can? :create, ::Template %>
Does show up.
<% end %>
<% if can? :read, Template %>
Does show up.
<% end %>
<% if can? :create, User %>
Does show up.
<% end %>
Upvotes: 2