I’m trying to figure out how to design a view and controller to work
with a
simple collection. I have a Foo that has many Bars, so here’s what I
did:
$ ruby script/generate model Foo
$ ruby script/generate model Bar
(Uncomment t.column, :name: :string in foo and bar migrations)
(Edit Foo.rb and Bar.rb, add has_many :bars to Foo, belongs_to :foo to
Bar)
$ rake db:migrate
$ ruby script/generate scaffold Foo
At this point you can create/edit foos, but no bars. So what I want to
be
able to do it create 5 bars at the same time I create a foo. So the
form
would look like this:
Name: []
Bar #1 Name: []
Bar #2 Name: []
Bar #3 Name: []
Bar #4 Name: []
Bar #5 Name: []
So, trying to follow the example from
ActionView::Helpers::FormHelper, I
added this to app/views/foos/_form.rhtml:
<% 5.times do |i| %>
<%= text_field 'bar[]', 'name' %>
But I get this error:
You have a nil object when you didn’t expect it!
You might have expected an instance of ActiveRecord::Base.
The error occured while evaluating nil.id_before_type_cast
Extracted source (around line #9):
6:
7: <% 5.times do |i| %>
8:
9: <%= text_field ‘bar[]’, ‘name’ %>
10: <% end %>
11:
12:
Hmmm… so I guess I need a bar array that is initialized with Bar
objects?
So I add this to the new method in the FooController:
@bars = []
5.times do |i|
@bars.push Bar.new
end
But then I get this error:
undefined method `id_before_type_cast’ for #Array:0x3925ee8
Extracted source (around line #9):
6:
7: <% 5.times do |i| %>
8:
9: <%= text_field ‘bars[]’, ‘name’ %>
10: <% end %>
11:
12:
So I’m stuck, how are you supposed to do this?