I have the following model structure:
class Test < ActiveRecord::Base
has_many :questions
end
class Question < ActiveRecord::Base
belongs_to :test
belongs_to :answer, class_name: 'Choice'
has_many :choices, dependent: :destroy
end
class Choice < ActiveRecord::Base
belongs_to :question
has_one :question_answered, dependent: :nullify, class_name: 'Question', foreign_key: 'answer_id'
end
Now I wanted to create a single form where the user could create/save the tests params and edit all the questions and their choices, and also select which one is the correct answer.
The problem arrives when the user is creating a new question. None of the choices have an id and, therefore, I don't know how to define which will be the correct answer without having to write extra code on my controller (only using accepts_nested_attributes_for).
What I did is: Before saving the nested attributes of Test (but saving test before), I fetch from params all the questions and choices that don't have an id and save them. After that I update the answer_id params for all the questions.
This solutions is working right now but I don't think it's the most elegant one. Knowing Rails and its awesomeness, I know there is a better way of doing this. What do you guys suggest?