簡體   English   中英

Cancancan - 定義:使用關聯創建

[英]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_commentPostsController方法,您可以這樣做...

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM