使用CanCan gem时遇到一些问题。
我有 ability.rb 档案:
if user.nil?
can :read, :all
elsif user.admin?
can :manage, Publication
else
can [:read, :create], Publication
can [:update, :destroy], Publication, :user_id => user.id
end
它是 publication.rb :
attr_accessible :content,:title
belongs_to :user
validates :user_id, presence: true
validates :title, presence: true, length: { maximum: 140 }
validates :content, presence: true, length: { minimum: 240 }
default_scope order: 'publications.created_at DESC'
发布的是index.html.erb:
<% @publications.each do |publicate| %>
<h3><%= publicate.title %></h3>
<% if can? :update, :destroy, Publication %>
<%= link_to "Update", edit_publication_path(publicate) %>
|<%= link_to " delete", publicate, method: :delete,
data: { confirm: "Are you sure?" } %>
<% end %>
<% end %>
并且它不显示delete
和Update
链接,如果是管理员或登录用户。
但如果我改变ability.rb
:
elsif user.admin?
can :manage, Publication
Publication
到User
,它有效,我在用户视图中看到链接删除:
<% @users.each do |user| %>
<li>
<%= link_to user.username, user %>
<% if can? :destroy, user %>
| <%= link_to "delete", user, method: :delete,
data: { confirm: "Are you sure?" } %>
<% end %>
</li>
<% end %>
而且user.admin can :manage, :all
,它也有效,并且与用户和出版物一起使用。为什么CanCan可以忽略出版能力?
答案 0 :(得分:0)
请阅读:
你应该明白为什么你的条件
can? :update, :destroy, Publication
不正确。您的操作为:update
,主题为:destroy
,您的第三个参数Publication
基本上被忽略。