AdilA
@AdilA
Нравится кодить, изучаю go c echo

Как в gem cancan разрешить юзеру комментировать только свои посты?

Чет никак не вкурю как разрешить юзеру который является создателем поста разрешить комментировать только свои записи но ему нельзя комментировать записи других!
В общем
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
  • Вопрос задан
  • 2640 просмотров
Решения вопроса 1
AMar4enko
@AMar4enko
can :add, Comment, attachable: {user_id: user.id}
can [:update, :delete], Comment, user_id: user.id

Предположил, что Comment у вас belongs_to: :user
Для того, чтобы проверить возможность добавления комментария нужно сделать что-то типа:
authorize! :add, @comment = Comment.new(attachable: @post)

За работоспособность не уверен, у меня больше Mongoid и Sequel и Rails нет
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы