I have the following db tables:
- Addresses - represents an address (ie line 1, line 2,
suburb,postcode, state and country)
- Accounts - represents a user account. Will have a foreign key,
- 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
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
@address = @account.address.build
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