1

I've tried following this advice but I haven't succeeded yet in generating a form containing 3 objects of the same type under one submit button.

When I navigate to a page that should show a form containing fields for 3 objects (called elements in this example) I get the following error: undefined method 'elements' for nil:NilClass
Any pointers would be much appreciated! My code is as follows:

app/controllers/elements_controller.rb

class ElementsController < ApplicationController
  def index
    @element_group = ElementGroup.new
    render 'pages/index'
  end
end

app/views/pages/home.html.erb

<%= render 'element_groups/form'%>

app/views/element_groups/_form.html.erb

<% form_for :element_group do |f|%>
  ## The error comes from this next line, as f.object is nil
  <% f.object.elements.each do |element| %>
    <% f.fields_for element do |element_form| %>
      <%= element_form.text_field :content %>
      <%= element_form.text_field :element_type %>
      <%= element_form.text_field :subtype %>
    <% end %>
  <% end %>
<% end %>

app/models/element_group.rb

class ElementGroup
  attr_accessor :elements

  def elements
    @elements = []
    3.times do
      @elements << Element.new
    end
    @elements
  end
end

app/models/element.rb

class Element < ActiveRecord::Base
  attr_accessible :element_type, :subtype, :content
end

db/schema.rb

  create_table "elements", :force => true do |t|
    t.string   "element_type"
    t.string   "subtype"
    t.string   "content"
    t.datetime "created_at"
    t.datetime "updated_at"
  end
Community
  • 1
  • 1
AJP
  • 26,547
  • 23
  • 88
  • 127

1 Answers1

0

Have you tried to change to <% form_for @element_group do |f|%> ?

Gerry
  • 5,326
  • 1
  • 23
  • 33
  • yeah. Then I get `undefined method 'model_name' for NilClass:Class` (originating from line 1 of element_groups/_form.html.erb) I believe this is due to the ElementGroup class in element_group.rb model not inheriting from ActiveRecord::Base but I just want to create a "fascade" model, that's just used for handling a set of other models as [this answer mentioned](http://stackoverflow.com/questions/972857/multiple-objects-in-a-rails-form). Do you think that's possible? – AJP Oct 06 '11 at 16:45
  • This is true I haven't noticed that you were not inheriting from `ActiveRecord::Base`. The answer you are referring is garbage. The sleekest way to do this is by following [this railscast](http://railscasts.com/episodes/196-nested-model-form-part-1). Hope I helped. – Gerry Oct 06 '11 at 21:06