如何在cancan中定义能力模型以允许用户使用关系编辑值?

时间:2013-03-29 07:37:54

标签: ruby-on-rails ruby-on-rails-3 cancan

以下是条件

users属于一个work,同样category属于一个work

现在我希望该特定作品的用户edit属于该作品的类别。

如何在ability模型中指定此内容?

编辑:

include CanCan::Ability

def initialize(user)

user ||= User.new # guest user

user.roles.each do |role|

role.name

if role.name == "admin"

    can :read, User

    can :create, User

    can :edit, User

    can :destroy, User

end

if role.name == "staff"

         can :read, :all

         can :create, :all

        cannot :edit, Category

        can :update, :all

        can :destroy, :all

       end

    if role.name == "others"

          can :read, :all

   end   

end 

end 

end

2 个答案:

答案 0 :(得分:0)

未经测试,但应该这样做:

can :manage, Category, :work_id => user.work_id

参考:https://github.com/ryanb/cancan/wiki/defining-abilities

答案 1 :(得分:0)

在能力等级中,您只传递用户。您还需要传递类别,

can :manage, Category if user.work_id == category.work_id  

或者你必须像这样迭代(我不推荐它),

can :manage, Category if user.work_id == user.work.categories.first.work_id  

此链接显示如何将多个参数发送到您的能力等级。

https://github.com/ryanb/cancan/wiki/Accessing-Request-Data