Search code examples
ruby-on-railsruby-on-rails-4cancan

How add cancan ability if i need user can create comments only for his posts?


In my app Users create Posts, and other Users with role "executor" create comments I use cancan, what I need to do if create comments can Users with role "executor" and User who create the Post but can not create comments to other Posts?

if user.has_role? :executor
    can :manage, [Responce, Comment]
  else
    can :read, :all
  end

if user.has_role? :customer
    can :manage, Post
    can :manage, Comment, :user => {user_id: user.id}
      else
    can :read, :all
  end

Comment.rb

class Comment < ActiveRecord::Base
    acts_as_nested_set :scope => :attachable

    belongs_to :attachable, :polymorphic => true
    has_many :comments, :as => :commentable
    belongs_to :user
end

class User < ActiveRecord::Base

    before_create :create_role


  has_many :posts
  has_many :comments, as: :attachable
  has_many :users_roles, dependent: :destroy
  has_many :roles, through: :users_roles


  def has_role?(role_sym)
    roles.any? { |r| r.name.underscore.to_sym == role_sym }
  end


  private
    def create_role
      self.roles << Role.find_by_name(:customer)  
    end
end

Solution

  • ability.rb

    can :add, Comment, attachable: {user_id: user.id}
    can [:update, :delete], Comment, user_id: user.id
    

    in controller CommentsCotroller

     @comment = Comment.new(com_params)
     authorize! :add, @comment = @comment