ruby-on-rails - 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
我应该在我的控制器动作中添加一些东西吗?我现在一片空白
解决方案
这样做的一种方法是创建一种方法来根据用户角色检查参数是否有效,
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 提供的等效检查方法。
希望这能回答你的问题!
推荐阅读
- javascript - 遍历对象并保存到地图以在表格上呈现
- go - 在失败的情况下管理生产者消费者死锁
- ssis - 使用变量作为条件拆分控件的输入
- autodesk-forge - Reality Capture 输出文件以伪造查看器
- php - PHP/PDO 中的 MySQL 连接处理问题
- material-ui - 将类从 Material-UI TextField 传递到 InputBase
- python - 如何处理我的 t3a 实例上的存储?
- javascript - “未定义 setTimeout”
- flutter - 固定类型时,根据 Flutter 中选择的项目更改整个底部导航栏的背景颜色
- python - Pythons 请求库从 URL 中删除附加问号