0

I am creating a quiz application. Here are my models.

Answers

class Answer < ActiveRecord::Base                                                                                       
belongs_to :question
end

Questions

class Question < ActiveRecord::Base
has_many :answers
belongs_to :correct_answer, :class_name=>"Answer" 
accepts_nested_attributes_for :answers,  :reject_if => lambda { |a| a[:content].blank?    }, :allow_destroy => true
end

I am trying to have a nested attributes form using the railscast 196 and 197 stuff. That way there can be infinite adds and removes when they are creating/editing.

I can create questions with answers that's fine. The issue is creating the correct_answer field. Since answers have not been saved yet, there is no id to put in the correct_answer_id form. Any ideas?

2 Answers2

0

I don't see a reason for the correct_answer field to be in the Question class. Why not add a boolean column to the answers table? Then you can do something like Question.answers.find(correct: true) to get a collection with all correct answers for the question. Then you can have questions with more than one correct answer too.

Max
  • 15,157
  • 17
  • 82
  • 127
  • DB wise having the correct_answer_id in the question means I don't have to iterate over the answers to get the correct one – user1169547 Feb 02 '12 at 03:44
  • No, this isn't true. You would use find to select the correct question out of the database. This would be one query, and will return one element. Even if you store the correct ID in the Question model, you will still need to query the answers database to pull the actual question. It really is poor design to store the correct answer in the Question model. Models are supposed to be encapsulated elements of your program. Don't mix questions and answers. – Max Feb 02 '12 at 04:39
0

Start with the end in mine.

I have done this myself - see What mysql database tables and relationships would support a Q&A survey with conditional questions?

Quiz applications have a long history of starting out very simple, then edge cases and wrinkles crop up. This design addresses many of them from experience.

If nothing else, some of the text with (my) answer may help you think things out.

Community
  • 1
  • 1
Michael Durrant
  • 93,410
  • 97
  • 333
  • 497