如何允许带有 * key => values 的散列?
How to permit hash with * key => values?
我想创建一个可以接受动态哈希键的强参数对象。
这是我的代码,
Quiz.create(quiz_params)
def quiz_params
params.require(:quiz).permit(:user_id, :percent, :grade, questions: {})
end
传入的数据看起来像这样。
// the keys that get passed into question is always different
quiz: {
user_id: 1,
percent: 80,
grade: "B",
questions: {
"12": "24",
"1": "12",
"4": "3",
"5": "22"
}
}
但是目前,当我尝试创建测验时,问题哈希结果为空。
到目前为止我只看到了这个:
def quiz_params
questions_params = (params[:quiz] || {})[:questions].keys
params.require(:quiz).permit(:user_id, :percent, :grade, questions: questions_params)
end
您是否考虑过更改 api?
quiz: {
user_id: 1,
percent: 80,
grade: "B",
answers_attributes: [
{
question_id: "12"
value: "24"
},
{
question_id: "3"
value: "12"
}
# ...
]
}
这就是 form_for
and nested_attributes
两者的工作方式。与其给自己一个潜在的大规模注入漏洞,不如重新考虑您的域建模。你可以做得更好。
在 rails 5.1.2 中,为 questions
传递空散列的原始语法应该有效:
def quiz_params
params.require(:quiz).permit(:user_id, :percent, :grade, questions: {})
end
见https://github.com/rails/rails/commit/e86524c0c5a26ceec92895c830d1355ae47a7034
我想创建一个可以接受动态哈希键的强参数对象。
这是我的代码,
Quiz.create(quiz_params)
def quiz_params
params.require(:quiz).permit(:user_id, :percent, :grade, questions: {})
end
传入的数据看起来像这样。
// the keys that get passed into question is always different
quiz: {
user_id: 1,
percent: 80,
grade: "B",
questions: {
"12": "24",
"1": "12",
"4": "3",
"5": "22"
}
}
但是目前,当我尝试创建测验时,问题哈希结果为空。
到目前为止我只看到了这个:
def quiz_params
questions_params = (params[:quiz] || {})[:questions].keys
params.require(:quiz).permit(:user_id, :percent, :grade, questions: questions_params)
end
您是否考虑过更改 api?
quiz: {
user_id: 1,
percent: 80,
grade: "B",
answers_attributes: [
{
question_id: "12"
value: "24"
},
{
question_id: "3"
value: "12"
}
# ...
]
}
这就是 form_for
and nested_attributes
两者的工作方式。与其给自己一个潜在的大规模注入漏洞,不如重新考虑您的域建模。你可以做得更好。
在 rails 5.1.2 中,为 questions
传递空散列的原始语法应该有效:
def quiz_params
params.require(:quiz).permit(:user_id, :percent, :grade, questions: {})
end
见https://github.com/rails/rails/commit/e86524c0c5a26ceec92895c830d1355ae47a7034