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
end
class Person < ActiveRecord::Base
has_many :dogs
end
# rails c
d = Dog.new
d.tags.build(:number => "123456")
d.save # => 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 = Dog.new
d.person.build # => nil object on nil.build
I have also tried
d = Dog.new
d.person = Person.new
d.save # => 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:
How does build work so that Rails is smart enough to figure out how to save the records in the right order?
How can I do the same thing in a
belongs_to
relationship?Where can I find any documentation on this method?
Thank you
belongs_to
" and "Methods Added byhas_one
". More technical documentation can be found in the API docs:belongs_to
andhas_one
. – Fustanella