Forum: Ruby on Rails Adding multiple rows of data using a single 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.
Kevin (Guest)
on 2007-01-25 01:12
I have a form where I want users to be able to add multiple names into a
database at once, instead of individually.

Currently my form is setup similar to this:

<% form_for(:owner, :url => owner_path) do |f| %>
First Name: <%= f.text_field :firstname  %>
Last Name: <%= f.text_field :lastname  %>

First Name: <%= f.text_field :firstname  %>
Last Name: <%= f.text_field :lastname  %>

First Name: <%= f.text_field :firstname  %>
Last Name: <%= f.text_field :lastname  %>
<% end %>

However, as expected this just adds the data from the first set of text
fields and ignores the others.

Any pointers on how I can allow the addition of multiple names at once?
Thanks.
unknown (Guest)
on 2007-01-25 08:49
(Received via mailing list)
Not sure of an elegant way to do it with form_for but perhaps this will
give you some ideas...

<% form_tag do %>
<% for @owner in @owners %>
<%= text_field("owner[]" , 'firstname') %><br />
<% end %>
<%= submit_tag %>
<% end %>

should work... note the "[]" on owner...

good luck!
Kevin (Guest)
on 2007-01-25 22:59
unknown wrote:
> Not sure of an elegant way to do it with form_for but perhaps this will
> give you some ideas...
>
> <% form_tag do %>
> <% for @owner in @owners %>
> <%= text_field("owner[]" , 'firstname') %><br />
> <% end %>
> <%= submit_tag %>
> <% end %>
>
> should work... note the "[]" on owner...
>
> good luck!

Thanks. I did find a way using form_for:

<% form_for(:owner, :url => owner_path) do |f| %>
<% (1..3).each do |i| -%>
First Name: <%= f.text_field :firstname, :index => i  %>
Last Name: <%= f.text_field :lastname, :index => i  %>
<% end -%>
<%= submit_tag "Add Names" %>
<% end %>

However, I now apparently need to make some changes to my controller for
this to work.

Here's the current create action:

def create
  @owner = Owner.new(params[:owner])
  if @owner.save
    flash[:notice] = 'Owner was succesfully added.'
    redirect_to :action => 'unpaid'
  else
    render :action => 'new'
  end
end

When submitting data, I get the following error:

NoMethodError in OwnersController#create
undefined method `1=' for #<Owner:0x260f4cc>
This topic is locked and can not be replied to.