Ruby on rails 为ActiveRecord继承层次结构定义CanCan功能的正确方法是什么?
我想为ActiveRecord类Ruby on rails 为ActiveRecord继承层次结构定义CanCan功能的正确方法是什么?,ruby-on-rails,inheritance,subclass,cancan,Ruby On Rails,Inheritance,Subclass,Cancan,我想为ActiveRecord类事物及其子类子项定义单独的能力。不幸的是,这不太可能,因为子类似乎继承了其父类的能力 我是这样开始的: class Ability include CanCan::Ability def initialize can :update, Thing can :update, SubThing do |st| st.editable? end end end class Ability include CanCa
事物
及其子类子项
定义单独的能力。不幸的是,这不太可能,因为子类似乎继承了其父类的能力
我是这样开始的:
class Ability
include CanCan::Ability
def initialize
can :update, Thing
can :update, SubThing do |st|
st.editable?
end
end
end
class Ability
include CanCan::Ability
def initialize
can :update, Thing
cannot :update, SubThing do |st|
!st.editable?
end
end
end
但是这不起作用,子项
总是可以更新的,不管它们的可编辑?
值是多少,因为子项
能力是从事物
继承的,它总是可更新的
我的结局是这样的:
class Ability
include CanCan::Ability
def initialize
can :update, Thing
can :update, SubThing do |st|
st.editable?
end
end
end
class Ability
include CanCan::Ability
def initialize
can :update, Thing
cannot :update, SubThing do |st|
!st.editable?
end
end
end
这是有效的:所有事物
s和子项
s都是可更新的,除了那些子项
s的可编辑?
值为false的除外。但依我看,这并不是一种直观的设置方式,而且能力课程似乎并没有完全表达我想要实现的目标
事实上,我更希望我的能力不是遗传的,这样我的第一种方法(IMHO更清楚地表达了我所追求的)就会起作用
有没有更好的方法来实现这一点
顺便说一句,这是一个可执行的测试用例,我写它是为了帮助理解并最终解决(解决?)我的问题。我不确定这是否会有帮助,但我通常倾向于使用Pundit()而不是CanCan,因为它是,IMHO,一种更灵活、更漂亮的方式,通过一个仅仅是PORO的策略系统来处理这种情况。希望如此help@lkartono是的,我知道Pundit,它看起来确实是CanCan的一个很好的替代品。但我正在开发一个传统的应用程序,其中CanCan已经就位。