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

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:

  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

This question is related to ruby-on-rails activerecord foreign-keys

The answer is


Where it is documented:

From the API documentation under the has_many association in "Module ActiveRecord::Associations::ClassMethods"

collection.build(attributes = {}, …) Returns one or more new objects of the collection type that have been instantiated with attributes and linked to this object through a foreign key, but have not yet been saved. Note: This only works if an associated object already exists, not if it‘s nil!

The answer to building in the opposite direction is a slightly altered syntax. In your example with the dogs,

Class Dog
   has_many :tags
   belongs_to :person
end

Class Person
  has_many :dogs
end

d = Dog.new
d.build_person(:attributes => "go", :here => "like normal")

or even

t = Tag.new
t.build_dog(:name => "Rover", :breed => "Maltese")

You can also use create_dog to have it saved instantly (much like the corresponding "create" method you can call on the collection)

How is rails smart enough? It's magic (or more accurately, I just don't know, would love to find out!)


@article = user.articles.build(:title => "MainTitle")
@article.save

Examples related to ruby-on-rails

Embed ruby within URL : Middleman Blog Titlecase all entries into a form_for text field Where do I put a single filter that filters methods in two controllers in Rails Empty brackets '[]' appearing when using .where How to integrate Dart into a Rails app Rails 2.3.4 Persisting Model on Validation Failure How to fix "Your Ruby version is 2.3.0, but your Gemfile specified 2.2.5" while server starting Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? Rails: Can't verify CSRF token authenticity when making a POST request Uncaught ReferenceError: React is not defined

Examples related to activerecord

Empty brackets '[]' appearing when using .where Get only records created today in laravel How do you manually execute SQL commands in Ruby On Rails using NuoDB Rails 4 LIKE query - ActiveRecord adds quotes Rails create or update magic? CodeIgniter query: How to move a column value to another column in the same row and save the current time in the original column? Check if record exists from controller in Rails Codeigniter's `where` and `or_where` Codeigniter LIKE with wildcard(%) Codeigniter: does $this->db->last_query(); execute a query?

Examples related to foreign-keys

Migration: Cannot add foreign key constraint The ALTER TABLE statement conflicted with the FOREIGN KEY constraint Can a foreign key refer to a primary key in the same table? Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why? MySQL Error 1215: Cannot add foreign key constraint MySQL Cannot Add Foreign Key Constraint Delete rows with foreign key in PostgreSQL How to remove constraints from my MySQL table? MySQL - Cannot add or update a child row: a foreign key constraint fails How to remove foreign key constraint in sql server?