2012-07-15 56 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