1

我正在尝试在 Rails 应用程序中设置 CanCan,但遇到了一些奇怪的行为。

我的ability.rb文件如下所示:

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

到目前为止,一切都很好。我去的时候 CanCan 没有抱怨/templates。奇怪的行为始于视图。can?询问时返回 false :createTemplate但询问:reador时返回 true 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 %>

哦,这是我的template.rb模型,以防万一:

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

这让我很困惑,为什么我只能在视图中获得某些权限,当它们在控制器中工作时?

4

1 回答 1

2

所以,问题是“模板”也是ActionView. 所以 CanCan 在控制器中查看我的模型,但ActionView::Template在视图中查看,而::Template我的模型是,我会考虑改变它。

<% if can? :create, ::Template %>
Does show up.
<% end %>

<% if can? :read, Template %>
Does show up.
<% end %>

<% if can? :create, User %>
Does show up.
<% end %>
于 2012-10-19T06:52:21.767 回答