Cancancan-定义:创建关联

问题描述

我在Ruby on Rails应用程序中遇到以下情况:

我有一个带有帖子的博客。每个帖子可以有1到 n 个作者,并且每个帖子都带有多个评论

class Post < ApplicationRecord
    has_many :comments,dependent: :destroy
    has_many :authors

class Comment < ApplicationRecord
    belongs_to :post

我正在使用CanCanCan进行授权。目前,每个人都可以在帖子上创建评论。我想通过在我的lock_comments模型上引入一个post属性,并相应地更改授权来更改它,使其功能如下:

  • 如果用户登录,则如果其父帖子上的:create为假,则允许评论lock_comments
  • 如果用户登录,则如果其父帖子上的:create为假,或者登录用户是该帖子的作者之一,则允许评论lock_comments

基本上,作者应该能够对自己的文章禁用评论,但是即使其他人禁用了评论,他们仍应该能够对自己的文章发表评论

我有点不知所措,在文档中找不到任何内容。我必须如何定义我的Ability才能起作用?

解决方法

我认为您无法在Ability中做到这一点,因为在您尝试访问create时,您不知道父职位是什么。如果create_commentPostsController方法,您可以这样做...

can :create_comment,Post do |post|
  !post.lock_comments || user.in?(post.authors)
end

但是如果它是create中的CommentsController,则需要使用before_action

class CommentsController < ApplicationController

  before_action :create_allowed,only: [:create]

  private

  def create_allowed
    post = Post.find(params[:comment][:post_id])
    return if post && (!post.lock_comments || current_user.in?(post.authors))
    flash[:error] = 'You are not allowed to do this'
    redirect_to root_path
  end
end