首页 > 解决方案 > Rails自引用表关联中基于角色的授权问题

问题描述

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

如果具有角色 customer 的用户可以使用 nil parent_id 创建问题并且具有角色 vendor 的用户可以使用问题 ID 的 parent_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

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

标签: ruby-on-railscontrollercancanself-reference

解决方案


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

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

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

希望这能回答你的问题!


推荐阅读