1

如何同时使用 cancan、inherited_resources 和单表继承?我有类似这个例子的代码:

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

当我以用户身份尝试创建人时,我得到 CanCan::AccessDenied。那是因为 InheritedResources 使用 Contact 作为 :resource_class。

4

1 回答 1

2

我找到了这个解决方案:

class ContactsController <  InheritedResources::Base
  alias :resource_class :contact_sti
end
于 2011-03-15T13:31:19.573 回答