无关联Model的ElectiveRecommendationsController参数白名单配置问题
解决无关联Model的Controller强参数配置问题
首先,强参数的核心是必须在controller的action里调用你定义的permitted_params方法来获取参数,不能直接用params里的原始值。另外要根据electives的实际参数结构调整permit的写法,分几种情况处理:
1. electives是单个普通参数(如字符串、数字)
如果你的请求参数是electives: "高等数学"这种单个值,你的permit写法本身没问题,但得确保action里正确调用:
class ElectiveRecommendationsController < ApplicationController def recommend # 一定要通过permitted_params取参数,别直接用params[:electives] chosen_electives = permitted_params[:electives] # 后续业务逻辑 end private def permitted_params params.permit(:electives) end end
2. electives是数组参数
如果请求里的electives是数组形式,比如electives: ["高等数学", "大学英语"],得改成数组声明的写法:
private def permitted_params params.permit(electives: []) end
3. electives是嵌套哈希参数
要是electives是嵌套的哈希结构,比如electives: { id: 1, name: "高等数学" },得指定允许的嵌套键:
private def permitted_params params.permit(electives: [:id, :name]) end
额外提醒
如果你的请求参数是被包裹在顶层命名空间下的(比如表单提交时自动生成的elective_recommendation[electives]),那得先指定顶层键再permit内部参数:
private def permitted_params params.require(:elective_recommendation).permit(:electives) end
内容的提问来源于stack exchange,提问作者user18487436
相关产品推荐
相关产品推荐

