我不太明白如何在 CanCan 的这种特殊情况下限制对链接的访问。我总是显示“编辑”链接。所以我认为问题在于我对cancan方法(load_和authorize_)的错误定义。我有这样的 CommentsController:
class CommentsController < ApplicationController
before_filter :authenticate_user!
load_resource :instance_name => :commentable
authorize_resource :article
def index
@commentable = find_commentable #loading our generic object
end
......
private
def find_commentable
params.each { |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.includes(:comments => :karma).find(value)
end }
end
end
我在 comments/index.html.erb 中有以下代码从其他控制器呈现文件:
<%= render :file => "#{get_commentable_partial_name(@commentable)}/show.html.erb", :collection => @commentable %>
在这种情况下,您可以将“#{get_commentable_partial_name(@commentable)}”视为“文章”。“articles/show.html.erb”的内容:
<% if can? :update, @commentable %>
<%= link_to 'Edit', edit_article_path(@commentable) %> |
<% end %>
我的能力.rb:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user
if user.role? :admin
can :manage, :all
elsif user.role? :author
can :read, [Article, Comment, Profile]
can :update, Article, :user_id => user.id
end
end
end
我试过像这样调试这个问题
user = User.first
article = Article.first
ability = Ability.new(user)
ability.can?(:update, article)
我总是在能力检查中得到“=> true”
注意:user.role == author and article.user_id != user.id
如果您需要更多信息,请写
谢谢你的时间&&对不起我的英语