Created
June 27, 2011 21:53
-
-
Save datapimp/1049943 to your computer and use it in GitHub Desktop.
nested attributes example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class ExamResult | |
| has_many :answers, :dependent => :destroy | |
| accepts_nested_attributes_for :answers | |
| # for cleaner API | |
| alias_method :user_answers=, :answers_attributes= | |
| end | |
| class Answer | |
| belongs_to :exam_result | |
| belongs_to :question | |
| before_save :check_answer | |
| def correct_answer_given? | |
| question.correct_answer == user_answer | |
| end | |
| def check_answer | |
| self.correct = correct_answer_given? | |
| true # return true so that it doesn't disrupt the after_save callback chain | |
| end | |
| end | |
| exam_result = ExamResult.new(:user_answers=>[{:user_answer=>"A",:question_id=>1},{:user_answer=>"B",:question_id=>2}]) | |
| exam_result.save # will create answer objects as well |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment