views:

39

answers:

1

I've got a nested form, structured: Question has_many Answers. So, the questions are multiple choice.

Current form view:

- semantic_form_for @question do |f|
  = f.error_messages
  - f.inputs do
    = f.input :question
    = f.semantic_fields_for :answers do |builder|
      = builder.input :content, :label => "Answer", :input_html => { :class => {'required', ' ckeditor'}}
    = f.buttons

My question controller looks like:

  def new
    @question = Question.new
    4.times { @question.answers.build }
  end

  def create
    @question = Question.new(params[:question])
    @question.user_id = current_user.id
    if @question.save
      flash[:notice] = "Question added."
      redirect_to questions_url
    else
      render :action => 'new'
    end
  end

All pretty simple. However, now I would like to 'select' the correct answer, preferably on the same page, while adding. I think I will add a new column to Questions containing 'CorrectAnswerId' of some sort. But, how can I add it in the view & controller?

+1  A: 

I am assuming you'd use some sort of checkbox method to indicate "This is the right answer".

In this case, you could simply have the checkbox contain the id of the answer and then on create you can set the correct_answer_id column to the id value of that checkbox.

However, because your answers have not been saved at this point (build only creates the objects in memory), you do not have the ids until the answers are already saved. The easiest solution is just to mark the answer as correct in the answers table, rather than in the questions table. Then you might create a method in the Question model like:

def correct_answer
    @correct ||= answers.where(:is_correct => true)
end

This will also give you the ability to allow for multiple correct answers if you need it. If this is not really going to be necessary, you can always just add .first to the end of the query string so that you return one answer rather than an array of correct answers.

Lukas
thx lukas! worked flawlessly. I made an easy jquery check to make sure there was only one checkbox checked at a time, works as well! :)
Maurice Kroon