rails 自引用 table 关联中基于角色的授权问题

Problem with role based authorization in rails self reference table association

我有一个关于名为 question_and_answers 的产品问答部分的自我参考 table,其中包含以下列:id、parent_id、text_field、user_id和 product_id。问题没有 parent_id,答案有 parent_id 个问题。用户有供应商和客户两种角色。

如果具有 customer 角色的用户可以使用 nil parent_id 创建问题并且具有 vendor 角色的用户可以使用 parent_id 创建答案,我如何在同一控制器操作中为问题和答案的创建操作编写代码问题的 id。我坚持如何让客户只创建问题,让供应商只创建答案。我正在使用 CanCan 进行基于角色的授权。

我的联想是这样的:

QuestionAndAnswer
belongs_to product, belongs_to user
has_many parent, class_name: QuestionAndAnswer, foreign_key: parent_id

User
has_many question_and_answers

Product 
has_many question_and_answers

我的控制器现在是这样的

class QuestionAndAnswersController < Api::BaseController
def create
   @thread = QuestionAndAnswer.new(thread_params)
   if @thread.save
     render json: @thread, status: :created
   else
     render status: 422 , json: {
     success: false,
     message: "Couldn't create thread"
   }
   end
end

def permitted_params
   [:parent_id, :textfield, :product_id, :user_id]
end

def thread_params
   params.permit(permitted_params)        
end
end

我应该在我的控制器操作中添加一些东西吗??我现在一片空白

一种方法是创建一个方法来根据用户角色检查参数是否有效,

def valid_params?
  has_parent = permitted_params[:parent_id].present?

  return false if current_user.vendor? && !has_parent
  return false if current_user.customer? && has_parent

  return true
end

然后在 create 操作中使用它

def create
   @thread = QuestionAndAnswer.new(thread_params)

   if valid_params? && @thread.save
     ...
   else
     ...
   end
end

当然,您需要用 cancan 提供的等效检查方法替换 current_user.vendor?current_user.customer?

希望这能回答您的问题!