CanCan、InheritedResources 和 STI
如何一起使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我找到了这个解决方案:
I found this solution: