I have in my view the following:
<% 0.upto(@num_performances) do |idx| -%>
<%= text_field ‘performance’, ‘city’, :index => idx, %>
<%= text_field ‘performance’, ‘venue’, :index => idx, %>
<% end -%>
and in my controller I have:
@performance = [Performance.new(“city” => “Toronto”, “venue” => “Opera
House”),
Performance.new(“city” => “Toronto”, “venue” =>
“The Rivoli”),
Performance.new(“city” => “Toronto”, “venue” =>
“The Gladstone”)]
but when I try to view this page, rails gives me the exception:
undefined method `city’ for #Array:0x8dac4f4
so it looks like rails is trying to send the “city” method to the
entire @performance array, rather than the element at the given index.
When I comment out the above @performance line, my view is rendered
and I get:
So I can post from this form to an action and I receive the following:
Parameters: { performance"=>{“0”=>{“city”=>“Toronto”, “time”=>"",
“date”=>"", “venue”=>“The Opera House”, “city_id”=>""},
“1”=>{“city”=>“Toronto”, “time”=>"", “date”=>"", “venue”=>“The
Social”, “city_id”=>""}, “2”=>{“city”=>"", “time”=>"", “date”=>"",
“venue”=>"", “city_id”=>""}}, … }
which I can easily turn into an array of Performance objects… But the
problem is, say the user posts this form and it has errors - I need to
re-populate the form fields, but I’m not sure how to get rails to take
an array of Performance objects and insert the appropriate elements
back into the corresponding text fields. I thought that by providing
an :index parameter to the text_field declaration, rails would realize
that it should send the method (such as ‘city’, or ‘venue’) to the
element of the array at that index, and not the entire array…
Of course I could just change my view so that I manually pull out the
information from the @performance array by iterating over it, but I
just wanted to check to see if there’s something I’m doing wrong
before going that route. Any information is greatly appreciated,
thanks.
Mike