我有一个模型MyQuiz,它通过问题属于测验,也属于用户
在模型上创建测验:测验和问题。因此模型MyQuiz是记录答案的模型
我使用的是SimpleForm,所以我想出了MyQuiz的这个表格
= simple_form_for(@my_quiz) do |f|
= f.error_notification
- @questions.each do |question|
.form-group
%p= question.title
= f.input :answer, as: :radio_buttons
= f.input :question_id, as: :hidden, :input_html => { :value => question.id }
= f.input :user_id, as: :hidden, :input_html => { :value => current_user.id }
.form-group
= f.button :submit, class: "btn btn-primary pull-right"
my_quizzes_controller.rb
def new
@quiz = Quiz.find(params[:quiz_id])
@questions = @quiz.questions.all
@my_quiz = MyQuiz.new
end
def create
@my_quiz = MyQuiz.new(my_quiz_params)
if @my_quiz.save
redirect_to user_path(@user), notice: "Thank you taking the quiz!"
else
render "new"
end
end
private
def my_quiz_params
params.require(:my_quiz).permit(:question_id, :user_id, :answer)
end
此表单的问题在于未正确设置序列化答案。所以它就好像所有答案都是一样的。甚至单选按钮的行为方式也相同
我不太确定我应该在这做什么。我也尝试过使用simple_fields_for的hacky解决方案,但它没有改变结果。
提前致谢
更新:使用建议和另一次尝试
所以建议将MyQuiz表格作为嵌套表格
类似的东西:
= simple_form_for @user do |g|
= g.error_notification
- g.simple_fields_for @my_quiz do |f|
- @questions.each do |question|
.form-group
%p= question.title
= f.input :answer, as: :radio_buttons
= f.input :question_id, as: :hidden, :input_html => { :value => question.id }
= f.input :user_id, as: :hidden, :input_html => { :value => current_user.id }
.form-group
= g.button :submit, class: "btn btn-primary pull-right"
我一直在玩这样的选项:
= form_tag my_quizzes_path do
- @questions.each do |question|
%p= question.title
= radio_button_tag "my_quizzes[#{question}][answer]", '0'
= radio_button_tag "my_quizzes[#{question}][answer]", '1'
= hidden_field_tag "my_quizzes[][question_id]"
= hidden_field_tag "my_quizzes[][user_id]"
= submit_tag "Submit"