我有一个应用程序,用户必须在其中填写调查。我需要将用户的答案存储在只有一个字段answers:string
的TestResult
模型中
在当前的实现中,我从表单中获得参数如下:
params => {
{
"question_#{id}": "some answer 1",
"question_#{id}": "some answer 12345",
}
}
我想更改为以下结构:
# expected hash params
params => {
{
question: 'first question',
answer: 'some answer 1'
},
{
question: 'second question',
answer: 'some answer 123431'
}
}
我应该更改什么(可能在视图中(才能获得此哈希?
new.html.erb
<%= simple_form_for :test_results, url: test_results_path do |f| %>
<% @randomize_questions.map do |q| %>
<%= q[:question] %>
<%= f.input "question_#{q[:id]}", collection: q[:answers], as: :radio_buttons %>
<% end %>
<%= f.button :submit %>
<% end %>
控制器:
class TestResultsController < ApplicationController
before_action :fetch_random_questions, only: [:new, :create]
def new
@test_result = TestResult.new
end
def create
@test_result = TestResult.new(
answer: test_result_params,
)
@test_result.save
redirect_to dummy_path
end
end
private
def test_result_params
params.require(:test_results).permit!
end
def fetch_random_questions
TestQuestion.where(published: true).order('RANDOM()')
@randomize_questions = test_questions.map do |obj|
{
id: obj.id,
question: obj.question,
answers: [obj.correct_answer, obj.other_answer1, obj.other_answer2, obj.other_answer3],
}
end
end
end
测试结果模型
类TestResult<应用程序记录serialize:answer,Hashserialize:answer,String验证:答案,存在:真结束
params从输入名称中获取其结构。
因此,您可以为问题添加一个隐藏字段,然后为两个字段指定一个名称。
<%= simple_form_for :test_results, url: test_results_path do |f| %>
<% @randomize_questions.map do |q| %>
<%= q[:question] %>
<%= f.input "question_#{q[:id]}", as: :hidden, input_html: { name: "test_results[#{q[:id]}][question]", value: q[:question] } %>
<%= f.input "question_#{q[:id]}", collection: q[:answers], as: :radio_buttons, input_html: { name: "test_results[#{q[:id]}][answer]" } %>
<% end %>
<%= f.button :submit %>
<% end %>
参数应该是这样的:
params => {
test_result: {
1 => {
question: "...",
answer: "..."
},
2 => {
question: "...",
answer: "..."
}
}
}
未测试你能告诉我这是否适合你吗?