Forum: Ruby on Rails New View Example With Child Object?

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.
A8c8f108223fa814980ad0c01411450c?d=identicon&s=25 Don Stocks (dstocks)
on 2006-01-14 00:43
Could somebody point me to some example code?  This must be simple, I
just can't find any examples.  I need a new view (new.rhtml) to include
the creation of a child object.  I have a table for servers (Servers)
and a table for IP Addresses (Ips).

Server
  has_many  :ips
Ip
  belongs_to :server

In my new.rhtml I want the IP entered to become a record in the Ips
table.  The Ips table is very simple.  It has two rows, id and
server_id.  Where would I look for example code for new.rhtml and
server_controller.rb?

Thanks for the help!

 - Don
A8c8f108223fa814980ad0c01411450c?d=identicon&s=25 Don Stocks (dstocks)
on 2006-01-17 01:05
Any suggestions here?  Thanks.

 - Don
25e11a00a89683f7e01e425a1a6e305c?d=identicon&s=25 Wilson Bilkovich (Guest)
on 2006-01-17 03:07
(Received via mailing list)
On 1/16/06, Don Stocks <amillionhitpoints@yahoo.com> wrote:
>
> Any suggestions here?  Thanks.
>
>  - Don
>

Here's an example that handles a one-to-one relationship between
servers.
Since you need multiple IPs per server, you'll want to work out some
way to address that in the view.  One way would be with Ajax and/or
RJS templates; another would be to let the user enter a
comma-separated list of IPs.. yet another would be to ask how many IPs
there will be up front, before showing the 'new' template, and build
that many form entries via a partial.

#server_controller.rb
  model :server
  model :ip

def new
  @server = Server.new(params[:server])
  @ip = Ip.new(params[:ip])
  @server.ips << @ip
  if request.post? and @server.save
    flash[:notice] = "All systems Go."
    redirect_to :action => 'show', :id => @server
  end
end

#new.rhtml
#I've omitted various useful things like labels, help text, etc.
<%= start_form_tag :action => 'new' %>
  <%= text_field 'server', 'some_property' %>
  <%= select 'server', 'something_else', some_list_of_options %>
  <%= text_field 'ip', 'address' %>
  <%= submit_tag "Create Server" %>
<%= end_form_tag %>

Every input field value for 'ip' will be available in params[:ip] once
this form is posted, and every 'server' input field will be found in
params[:server].

Saving the parent object (@server) also saves any unsaved children, so
the new Server and Ip objects are both saved in one step.
This topic is locked and can not be replied to.