Problem with validates_associated and validates_presence_of

This is really confusing me. I have some model similar to the one

class Question << ActiveRecord:Base
has_many :options
has_many :answers

 validates_presence_of :answer

class Option << ActiveRecord:Base
belongs_to :question
has_one :answer
class Answer << ActiveRecord:Base
belongs_to :question
belongs_to :answer

validates_presence_of :option_id


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.
o1 =
a1 = (:option => o1)

Now when I do or! 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 = => 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.


Just in case anybody faces this problem: I solved it by using
“validates_associated” to validate the presence of associations. Using
“validates_presence_of” for this purpose gave me the same problems as
the original poster.