Question about using ".build" in association with has_one and belongs_to

hi, guys,

I have the following db tables:

  1. Addresses - represents an address (ie line 1, line 2,
    suburb,postcode, state and country)
  2. Accounts - represents a user account. Will have a foreign key,
  3. Warehouses - represents a warehouse. Will have a foreign key,

Each Account object can have one or zero (none) corresponding Address
Each Warehouse object can have one or zero (none) corresponding
Address object.

I started off reading


on the “.build” helper.

From what I understand in context of the latter url, the model
assigned with the “belongs_to” will have a foreign key attribute.

In my case, consider that a new Account is being created (via
The user goes to his/her profile and clicks on the “create new
Address” to fill in his/her address for the account.

The Addresses controller’s ‘new’ method is called.
This is where I am stuck.

If i did something like

def new
@address =

this will cause a new Addresses object to be built with a non-existent
attribute, :user_id to be set with the new address’ id.

An option I have considered is to set the address id value into the
Account object’s foreign key, ‘:address_id’ when
a new address is being submitted for creation (ie. calling Addresses
controller method, ‘create’).
Here’s an example:

def create
    @address =[:address])

    if =
       flash[:notice] = "Account registered!"
       redirect_back_or_default account_url
      render :action => :new

Is there a better way to set the foreign key of an object when an
optionally associated object is being instantiated and saved to the