2012-07-15 53 views
2

我试图阻止各种项目的编辑能够使用cancan发布自己的作品,但它不能按预期工作。迄今为止的其他一切都很完美。rails cancan自定义动作

例如:

can :publish, [Article, Review] do |doc| 
    doc.user != @user 
end 

查看

<% if can? :publish, @review %> 

我遵循设置自定义操作的文档,但到目前为止,我还没有成功。

https://github.com/ryanb/cancan/wiki/Custom-Actions

ability.rb

class Ability 
    include CanCan::Ability 

    def initialize(user) 
    @user = user || User.new # for guest 
    @user.roles.each { |role| send(role) } 

    if @user.roles.size == 0 
     can :read, :all #for guest without roles 
    end 
    end 

    def author 
    can :manage, [Article, Review] do |doc| 
     doc.try(:user) == @user 
    end 
    can :submit, [Article, Review] 
    end 

    def editor 
    can :manage, [Article, Review] 
    can :publish, [Article, Review] do |doc| 
     doc.user != @user 
    end 
    end 

    def admin 
    can :manage, :all 
    can [:submit, :publish, :reject], [Article, Review] 
    end 
end 

回答

3

我认为你要做到这一点

cannot :publish, [Article, Review], :user_id => @user.id 

这是说,用户不能发布,如果一篇文章或评论文章的创造者是他们。

例如,在我的应用程序中,我有一个登录用户可以创建新问题的位置。用户可以管理自己的问题,用户可以对问题进行投票。但是,用户不能对自己的问题投票。这听起来很熟悉吗? :)

can [:new, :create], Question 
    can :manage, Question, :user_id => user.id 
    can :vote, Question 
    cannot :vote, Question, :user_id => user.id