user1436111
user1436111

Reputation: 2141

Rails form - Iterating over collection in form

In my form I want to iterate over a specific collection and collect the same information about each. For simplicity's sake something like:

<%= form_tag :update_dog do %>
    <% @dogs.each do |dog| %>
        <%= text_field_tag :name, :class=>dog.id %>
    <% end %>
    <%= submit_tag "Add", :class => 'btn btn-success'%>
<%= end %>

Where I would want to collect each dog's name to manipulate in the controller (in which I'd like to be able to iterate over each submitted dog name and access its id). The potential number of dogs in my collection is variable. What is the best way to do this? The code above is what I have so far but I have no idea if it's right and if so, how to use it in the controller.

Thanks so much!

Upvotes: 1

Views: 119

Answers (1)

RadBrad
RadBrad

Reputation: 7304

I'd start with a filter. Create a before_filter that creates your dogs

class KennelController < ApplicationController
  before_filter  :get_dogs , :only=>[:new,:edit]
  def get_dogs
     @dogs = Dog.all.map{|d| [d.name, d.id]}
  end
  ....
end

Then in either your new or edit views, you could do this:

<%= select_tag :dog, options_for_select(@dogs) %>

Upvotes: 1

Related Questions