Answer the question
In order to leave comments, you need to log in
How to allow users to comment only on their own posts in gem cancan?
I don’t even know how to allow the user who is the creator of the post to allow commenting only on his own posts, but he can’t comment on the posts of others!
In general
User.rb
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
class Post < ActiveRecord::Base
belongs_to :user
end
class Role < ActiveRecord::Base
has_many :users_roles
has_many :users, through: :users_roles
end
class UsersRole < ActiveRecord::Base
belongs_to :user
belongs_to :role
end
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # in case of guest
if user.has_role? :admin
can :manage, :all
else
can :read, :all
end
if user.has_role? :customer
can :manage, Post
can :manage, Comment, Comment.where(attachable_type: Post, attachable_id: user.post.id)
else
can :read, :all
end
end
Answer the question
In order to leave comments, you need to log in
can :add, Comment, attachable: {user_id: user.id}
can [:update, :delete], Comment, user_id: user.id
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question