NOOB: Representing linked objects in one form


#1

Given two models:

User
:name
:email
:address_id # foreign key

Address
:line_1
:line_2
:city

etc.

I want to have a form allowing a user to register, in which she’d enter
an address as well, but how do I go about combining both objects into
the one form?

I’m new to this and following along with the Agile Rails book from the
Pragmatic Programmers, but it doesn’t mention this and I’m having
trouble getting a decent answer with searches.


#2

have a look over there : www.ajaxscaffold.com

Thibaut


#3

I’m not sure that it’s ajax that’s needed here as such.

The address fields on the form will look something like this:


You should then be able to create a new address via the user object in
your controller:

def register_user
user = User.new(params[:user])
if user.save
user.addresses.create(params[:address])
end
end

I might be wrong but i would think that you need to have a user_id in
‘addresses’ rather than an address_id in ‘users’ - the above assumes
that this is the case. It also assumes that users have many addresses.

Hope this helps,

Steve


#4

To keep with the Rails style, the text fields should look like this:

<%= text_field ‘address’, ‘line_1’ %>
<%= text_field ‘address’, ‘line_2’ %>
<%= text_field ‘address’, ‘city’ %>

and Steve is right: if a user has_one or has_many addresses, the foriegn
id field should be in the address table.

-Adam


#5

Oops. Looks like I’ve more fundamental problems to be worrrying about.
Thanks!