D
D
dexdev2014-09-10 11:05:46
Ruby on Rails
dexdev, 2014-09-10 11:05:46

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

1 answer(s)
_
_ _, 2014-09-10
@AdilA

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

I assumed that your Comment belongs_to: : user
In order to check the possibility of adding a comment, you need to do something like:
I'm not sure about the performance, I no longer have Mongoid and Sequel and Rails

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question