ruby-on-rails association activerecord - Ruby on Rails. How do I use the Active Record .build method in a :belongs to relationship?

1 Answers

@article = => "MainTitle")
vs new create

I have been unable to find any documentation on the .build method in Rails (i am currently using 2.0.2).

Through experimentation it seems you can use the build method to add a record into a has_many relationship before either record has been saved.

For example:

class Dog < ActiveRecord::Base
  has_many :tags
  belongs_to :person

class Person < ActiveRecord::Base
  has_many :dogs

# rails c
d = => "123456") # => true

This will save both the dog and tag with the foreign keys properly. This does not seem to work in a belongs_to relationship.

d = # => nil object on

I have also tried

d =
d.person = # => true

The foreign key in Dog is not set in this case due to the fact that at the time it is saved, the new person does not have an id because it has not been saved yet.

My questions are:

  1. How does build work so that Rails is smart enough to figure out how to save the records in the right order?

  2. How can I do the same thing in a belongs_to relationship?

  3. Where can I find any documentation on this method?

Thank you