我为产品的问答部分提供了一个自我参考表,名为question_and_answers,其列为:id,parent_id,text_field,user_id和product_id。问题没有parent_id,答案有问题的parent_id。用户具有供应商和客户两个角色。
如果具有角色customer的用户可以使用nil parent_id创建问题,而具有角色卖方的用户可以使用问题的id的parent_id创建答案,那么如何在同一控制器操作中为问题和答案的create操作编写代码。我在如何让客户只创建问题而让供应商只创建答案方面陷入困境。我正在使用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?
。
希望能回答您的问题!