1

How can I use cancan, inherited_resources and single table inheritance together? I have code similar this example:

class Contact < ActiveRecord::Base; end
class Person < Contact; end
class Company < Contact; end

class Ability
  include CanCan::Ability
  def initialize(user)
    user ||= User.new # in case of guest
    can :read, Contact # User can read People and Companies
    can :create, Person # User can create Person only
    can :manage, :all if user.has_role? :admin
  end
end

class ContactsController <  InheritedResources::Base
  load_and_authorize_resource
  def new
   @contact = contact_sti.new
  end

  private
  def clazz
     self.params[:contact_type].nil? ? "contact" : self.params[:contact_type]
  end
  def contact_sti
    clazz.camelize.constantize
  end
end

When I try as a User to create Person I get CanCan::AccessDenied. That's because InheritedResources use Contact as :resource_class.

boblin
  • 3,541
  • 4
  • 25
  • 29

1 Answers1

2

I found this solution:

class ContactsController <  InheritedResources::Base
  alias :resource_class :contact_sti
end
boblin
  • 3,541
  • 4
  • 25
  • 29