Currently working on nested forms with the following railscast http://railscasts.com/episodes/196-nested-model-form-revised
I have an Opportunity model,
class Opportunity < ActiveRecord::Base
has_many :headings
accepts_nested_attributes_for :headings
end
a Heading model
class Heading < ActiveRecord::Base
belongs_to :opportunity
has_many :subheadings
accepts_nested_attributes_for :subheadings
end
and a Subheading model
class Subheading < ActiveRecord::Base
belongs_to :heading
end
Right now I am just working on the view for the new action for the Opportunity model.
<h1>Add an opportunity</h1>
<%= form_for(@opportunity, :html => {:role => 'form'}) do |f| %>
<%= f.fields_for :headings do |builder| %>
<%= render 'heading_fields', f: builder %>
<% end %>
<%= link_to_add_fields "Add heading", f, :headings %>
<%= f.submit %>
<% end %>
And the _heading_fields.html.erb partial:
<fieldset>
<%= f.label :title, "Heading" %>
<%= f.text_field :title %>
<%= f.hidden_field :_destroy %>
<%= link_to "Remove section", '#', class: "remove_fields" %>
<%= link_to_add_fields "Add section", f, :subheadings %>
</fieldset>
And finally the link_to_add_fields method in the application helper:
def link_to_add_fields(name, f, association)
new_object = f.object.send(association).klass.new
id = new_object.object_id
fields = f.fields_for(association, new_object, child_index: id) do |builder|
render(association.to_s.singularize + "_fields", f: builder)
end
link_to(name, '#', class: "add_fields", data: {id: id, fields: fields.gsub("\n", "")})
end
Now I am receiving the following error for the render call in the link_to_add_fields function:
syntax error, unexpected tIDENTIFIER, expecting keyword_end
It seems to have something to do with the underscore in the name of the partial being rendered in the link_to_add_fields method as it goes away when the underscore is not present.
Greatly appreciate any help at solving this headache!