Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 为ActiveRecord继承层次结构定义CanCan功能的正确方法是什么?_Ruby On Rails_Inheritance_Subclass_Cancan - Fatal编程技术网

Ruby on rails 为ActiveRecord继承层次结构定义CanCan功能的正确方法是什么?

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

我想为ActiveRecord类
事物
及其子类
子项
定义单独的能力。不幸的是,这不太可能,因为子类似乎继承了其父类的能力

我是这样开始的:

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已经就位。