Skip to content

Instantly share code, notes, and snippets.

@datapimp
Created June 27, 2011 21:53
Show Gist options
  • Select an option

  • Save datapimp/1049943 to your computer and use it in GitHub Desktop.

Select an option

Save datapimp/1049943 to your computer and use it in GitHub Desktop.
nested attributes example
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