Forum: Ruby on Rails NOOB: Representing linked objects in one form

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
71a6acd64a1e2e3c7577c9ee8c904f7b?d=identicon&s=25 donncha (Guest)
on 2006-05-17 14:57
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.
91eb330fb36d1e03c856574dfb77d2bc?d=identicon&s=25 Thibaut Barrère (thbar)
on 2006-05-17 15:40
(Received via mailing list)
have a look over there :  www.ajaxscaffold.com

Thibaut
882cc23c77c5c6d27613c51396a02a0d?d=identicon&s=25 Stephen Bartholomew (Guest)
on 2006-05-17 15:56
(Received via mailing list)
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:
<input type="text" name="address[line_1]"/>
<input type="text" name="address[line_2]"/>
<input type="text" name="address[city]"/>

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
6ec1e89eef5ce09fbfa56be5b6dd17b5?d=identicon&s=25 Adam Bloom (admanb)
on 2006-05-17 18:01
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
71a6acd64a1e2e3c7577c9ee8c904f7b?d=identicon&s=25 donncha (Guest)
on 2006-05-18 01:47
Oops. Looks like I've more fundamental problems to be worrrying about.
Thanks!
This topic is locked and can not be replied to.