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,
    “address_id”
  3. Warehouses - represents a warehouse. Will have a foreign key,
    “address_id”

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

I started off reading


and
http://guides.rubyonrails.org/getting_started.html#associating-models
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
registration).
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 = @account.address.build
end

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.new(params[:address])

    if @address.save
       @user.id = @address.id
       @user.save
       flash[:notice] = "Account registered!"
       redirect_back_or_default account_url
    else
      render :action => :new
    end
end

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
db?

thanks

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs