0

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?

Thiago
  • 337
  • 2
  • 12
  • I would rephrase the question body, so it asks less about refactoring, and relates more to the question title. If your code works right now, show a case where it does not work, if possible. – onebree Sep 11 '15 at 14:52
  • I am sorry. Maybe I should rephrase the title. The code does work, it's just that I am not happy with what I did to make it work. As I said in the body. – Thiago Sep 11 '15 at 15:07

0 Answers0