この特定のケースで 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 == 作成者および article.user_id != user.id
さらに情報が必要な場合は、書いてください
お時間をいただきありがとうございます && 私の英語で申し訳ありません