CanCan polymorphic resource access problem

Posted by Call 'naive' True on Stack Overflow See other posts from Stack Overflow or by Call 'naive' True
Published on 2011-01-15T16:43:24Z Indexed on 2011/01/15 17:53 UTC
Read the original article Hit count: 226

Hi everybody,
i don't quite understand how to restrict access to links in this particular case with CanCan. I always get "Edit" link displayed. So i believe the problem is in my incorrect definition of cancan methods(load_ and authorize_). I have CommentsController like that:

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

and i have in comments/index.html.erb following code that render file from other controller:

<%= render :file => "#{get_commentable_partial_name(@commentable)}/show.html.erb", :collection => @commentable %>

you can think about "#{get_commentable_partial_name(@commentable)}" like just "articles" in this case. Content of "articles/show.html.erb":

<% if can? :update, @commentable %>
    <%= link_to 'Edit', edit_article_path(@commentable) %> |
<% end %>

my ability.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

relations with models is:

class Comment < ActiveRecord::Base
  belongs_to :commentable, :polymorphic => true, :dependent => :destroy
  ...
end

class Article < ActiveRecord::Base 
  has_many :comments, :as => :commentable, :dependent => :destroy
  ...
end

i have tried debug this issue like that

user = User.first
article = Article.first
ability = Ability.new(user)
ability.can?(:update, article)

and i always get "=> true" in ability check

Note: user.role == author and article.user_id != user.id

if you need more information please write

thank's for your time && sorry for my english

© Stack Overflow or respective owner

Related posts about ruby-on-rails-3

Related posts about polymorphic-associations