【发布时间】:2021-07-08 12:12:52
【问题描述】:
我有一个应用程序,用户必须在其中填写调查问卷。我需要将用户的答案存储在 TestResult 模型中,该模型只有一个字段 answers:string
通过当前的实现,我从表单中获取参数:
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
【问题讨论】:
-
TestResult 看起来如何?它是 question_id 和 answer_id 的组合还是文本?
-
@Joel_Blum 问题已更新,它只是一个表字段
answer我想将所有答案存储为哈希
标签: ruby-on-rails