2

I'm trying to prevent editors of various items from being able to publish their own works using cancan but it doesn't work as expected. Everything else so far works perfectly.

For example:

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

View

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

I followed the docs for setting up a custom action but so far I have not had any success.

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
Community
  • 1
  • 1
holden
  • 13,471
  • 22
  • 98
  • 160

1 Answers1

3

I think that you're looking to do this

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

This is saying that the user cannot publish an Article or Review if the creator of the article is them.

For example, in my app, I have where a user that is logged in can create new Questions. Users can manage their own questions and users can vote on questions. However, a user cannot vote on their own question. Does this sound familiar? :)

  can [:new, :create], Question
  can :manage, Question, :user_id => user.id
  can :vote, Question
  cannot :vote, Question, :user_id => user.id
kobaltz
  • 6,980
  • 1
  • 35
  • 52