This is really confusing me. I have some model similar to the one below
class Question << ActiveRecord:Base has_many :options has_many :answers
validates_presence_of :answer end class Option << ActiveRecord:Base belongs_to :question has_one :answer end class Answer << ActiveRecord:Base belongs_to :question belongs_to :answer
validates_presence_of :option_id end
What I am trying to achieve is something like this -
If a question has two options (option id 1 & 2) and the correct answer is option 1, then an entry should be made in answer with the corresponding question id and option id.
Now as shown above, if I put a validates_presence_of in answer, it works fine when I play with it from the console. I create a new option, do not save it and then create a new answer that is associated with the option. Example: o1 = Option.new a1 = Answer.new (:option => o1)
Now when I do a1.save or a1.save! they work fine and I get no errors and the appropriate entries are made in the database. However, the problem comes in when I try achieving this through the GUI.
In the GUI, I have a form for question and I've embedded a form for Option through fields_for. Now, in the controller, based on some input from GUI ( a hidden field that passes the option_sequence), I find the option, create a new Answer like
answer = Answer.new(:option => option, :question => question) and also added this to the question question.answers << answer
Now all the three are new. When I click on Create/Submit button, I get errors saying, Option can't be blank and Answer is invalid.
However, if I remove the validation for presence of option, it works and the option id as well as question id are correctly persisted.
Secondly, if I replace the validates_presence_of to check for :option instead of option_id, even then it works.
I read in a ticket that option_id should be validated and not the option. Besides, why does this work from the console and not from the view. Is the code in the controller incorrect?
Any help is appreciated.
Thanks!