I have a QuestionResult, which has_and_belongs_to_many Answers and which has a custom validate to ensure there is at least one Answer associated.
As advertised on
http://wiki.rubyonrails.org/rails/pages/has_and_belongs_to_many , the following test fails:
question_result = QuestionResult.new(:question => @question, :interview_result => @interview_result)
question_result.answers << @answer question_result.save! # => throws RecordInvalid (at least one answer is required)
The save! fails because I should be saving question_result before adding relationships through the << call (otherwise the id is not already known).
My current solution is to bypass the validations using save(false), then add the answers, then call save!, and wrap all the code with a begin/rescue to remove the question_result when RecordInvalid is thrown (I could also use a transaction for the job).
Is there any cleaner or shorter way to achieve this ?