Search code examples
ruby-on-railsruby-on-rails-3simple-form

why i lost radio button created by simple form when submit an form with error?


I have a form like this:

new question

When i submit form without any content, it shows errors:

error new question

The radio button is lost !

This is in my form view:

<%= simple_form_for @question, defaults: { error: false } do |q| %>

  <legend>Question</legend>
  <%= render "shared/error_messages", object: q.object %>

  <%= q.input :content, input_html: { rows: 3, class: 'span6' } %>
  <%= q.input :mark, input_html: { class: 'span1' } %>
  <%= q.association :topic %>
  <%= q.association :question_type %>

  <%= q.simple_fields_for :answers do |a| %>
    <%= a.input :correct, collection: [[true, 'True'], [false, 'False']],
                                                            as: :radio_buttons,
                                                            label: 'Answer',
                                                            value_method: :first,
                                                            label_method: :last,
                                                            item_wrapper_class: 'inline'
                                                            %>
  <% end %>
<% end %>  

What's i missed or wrong? I used render 'new' in my create action of Question controller when @question.save is false. This is my question controller:

class QuestionsController < ApplicationController
  def new
    @question = Question.new
    @question.answers.build
  end

  def create
    @question = Question.new(content: params[:question][:content])
    @question.mark = params[:question][:mark]
    @question.topic_id = params[:question][:topic_id]
    @question.question_type_id = params[:question][:question_type_id]
    @question.user_id = current_user.id

    if @question.save
      if params[:question][:answers_attributes]['0'][:correct] == 'true'
        answer = @question.answers.build(content: 'True')
        answer.correct = true
      else
        answer = @question.answers.build(content: 'False')
      end
      if @question.save
        flash[:success] = "Successfully created new question."
        redirect_to root_url
      else
        render 'new'
      end
    else
      render 'new'
    end
end

Solution

  • Added @question.answers.build above last render 'new' and it works now