CanCan、InheritedResources 和 STI

发布于 2024-10-22 01:26:08 字数 874 浏览 6 评论 0原文

如何一起使用 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

当我尝试作为用户创建 Person 时,我得到 CanCan::AccessDenied。这是因为 InheritedResources 使用 Contact 作为 :resource_class。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一绘本一梦想 2024-10-29 01:26:08

我找到了这个解决方案:

class ContactsController <  InheritedResources::Base
  alias :resource_class :contact_sti
end

I found this solution:

class ContactsController <  InheritedResources::Base
  alias :resource_class :contact_sti
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文