2015-04-07 27 views
2

我有一个复杂的规则,我似乎无法定义,用户可以阅读他们自己的信件,或者如果他们有权限,他们可以阅读未链接到其他人的信件类型(如果它们是那些看到它的类型控件)。在Cancancan中定义组合复杂能力规则

class Letter < ActiveRecord::Base 
    belongs_to :letter_template 
    has_one :letter_template_type, through: :letter_template 
end 

class LetterTemplateType < ActiveRecord::Base 
    has_and_belongs_to_many :types 
end 

我已经试过了,以为它会掩盖它,但看着生成的SQL它的“或(不信匹配规则)”而不是“与(不是字母匹配规则)”。

can :read, Letter 
cannot :read, Letter, letter_template_type: { types: { active: [true, false] } } # the active [true, false] is just to find any type 

我尝试的另一种方法是用块/范围,但随后抱怨 “康康舞::错误: 无法合并与其他条件的活动记录范围而不是使用哈希或SQL用于读字符。能力。”

can :read, Letter, Letter.without_type do |l| 
    l.letter_template_type.nil? || l.letter_template_type.types.empty? 
end 

任何人都可以帮我定义这种情况的规则吗?

回答

0

使用这样,

can :read, Letter, [] do |l| 
    l.letter_template_type.nil? || l.letter_template_type.types.empty? 
end 

您也可以在上述块添加a user can read their own letters条件,可能是它是l.user == your_ability_user

+0

感谢jon的回应,我还没有机会尝试,但我的第一个担心是,它不适用于accessible_by调用? – miegs3

+0

是的,它可以工作,但'accessible_by'为您提供所有记录。所以为了授权资源,你必须明确地写'授权! :在每种方法中显示,@ user'和块条件起作用。 –