Search code examples
ruby-on-railsrubyactiverecordruby-on-rails-3.1model

Nested model creation in rails


I'm playing around with the Rails Console and was wondering why the following code doesn't work:

Question.create(body: "Why this does not work?", answer_attributes: {body: "Some Answer"})

It's weird cause when I do this:

question = Question.new(body: "Why this does not work?", answer_attributes: {body: "Some Answer"})
question.answer

I get something that looks like this:

=> #<Answer id: nil, body: "Some Answer", question_id: nil, created_at: nil, updated_at: nil>

It seems that the answer object is associated with the question object...

Now if I try to save the object, it doesn't work:

question.save

I get this:

 => false

When I call .errors on it I get this:

question.errors
@messages={:"answer.question_id"=>["can't be blank"]}>

Both objects are new so it's kinda normal the question object doesn't have an id.

I know I could create the answer object by creating a question first and then call update_attributes on it... Or simply by creating a question and then calling answers.build on it...

My question is... Is there a way for a child model to get its parent's id upon creation?

Oh and if you're wondering, I do have a validation that requires an answer to have a question_id value.

thx!


Solution

  • I finally found an answer to my question...

    I needed to put this code:

    :inverse_of => :question
    

    So my question model would look like this:

    class Question < ActiveRecord::Base
      has_many :answers, :dependent => :destroy, :inverse_of :question
    
      accepts_nested_attributes_for :answers
    end
    

    My answer model would look like this:

    class Answer < ActiveRecord::Base
      belongs_to :question
    
      validates :question, :presence => true
    end