[英]Cancancan - define :create with association
我的 Ruby on Rails 應用程序中有以下情況:
我有一個有帖子的博客。 每個帖子可以有 1 到n 個作者,並且每個帖子都與幾個評論相關聯:
class Post < ApplicationRecord
has_many :comments, dependent: :destroy
has_many :authors
class Comment < ApplicationRecord
belongs_to :post
我正在使用 CanCanCan 進行授權。 目前,每個人都可以對帖子發表評論。 我想通過在我的post
模型上引入lock_comments
來改變這一點,並相應地更改授權,使其功能如下:
:create
if lock_comments
on lock_comments
parent post 為 false:create
如果其父帖子上的lock_comments
為 false,則:create
,或者登錄用戶是該帖子的作者之一基本上,作者應該能夠禁用對他們文章的評論,但他們仍然應該能夠對自己的文章發表評論,即使其他人的評論被禁用。
我在這里有點不知所措,在文檔中找不到任何內容。 我必須如何定義我的Ability
才能使其發揮作用?
我認為您無法在 Ability 中執行此操作,因為在您嘗試訪問create
您不知道父帖子是什么。 如果create_comment
是PostsController
方法,您可以這樣做...
can :create_comment, Post do |post|
!post.lock_comments || user.in?(post.authors)
end
但是,如果它是在CommentsController
create
,則需要使用before_action
來執行此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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.