How Do I Prevent Rails From Treating Updated Nested Attributes Differently From New Nested Attribute

Posted by James on Stack Overflow See other posts from Stack Overflow or by James
Published on 2010-05-19T03:17:39Z Indexed on 2010/05/19 3:20 UTC
Read the original article Hit count: 510

I am using rails3 beta3 and couchdb via couchrest. I am not using active record.

I want to add multiple "Sections" to a "Guide" and add and remove sections dynamically via a little javascript. I have looked at all the screencasts by Ryan Bates and they have helped immensely. The only difference is that I want to save all the sections as an array of sections instead of individual sections. Basically like this:

"sections" => [{"title" => "Foo1", "content" => "Bar1"}, {"title" => "Foo2", "content" => "Bar2"}]

So, basically I need the params hash to look like that when the form is submitted. When I create my form I am doing the following:

<%= form_for @guide, :url => { :action => "create" } do |f| %>
  <%= render :partial => 'section', :collection => @guide.sections %>   
  <%= f.submit "Save" %>
<% end %>

And my section partial looks like this:

<%= fields_for "sections[]", section do |guide_section_form| %>
  <%= guide_section_form.text_field :section_title %>
  <%= guide_section_form.text_area :content, :rows => 3 %>
<% end %>

Ok, so when I create the guide with sections, it is working perfectly as I would like. The params hash is giving me a sections array just like I would want. The problem comes when I want edit guide/sections and save them again because rails is inserting the id of the guide in the id and name of each form field, which is screwing up the params hash on form submission.

Just to be clear, here is the raw form output for a new resource:

<input type="text" size="30" name="sections[][section_title]" id="sections__section_title">
<textarea rows="3" name="sections[][content]" id="sections__content" cols="40"></textarea>

And here is what it looks like when editing an existing resource:

<input type="text" value="Foo1" size="30" name="sections[cd2f2759895b5ae6cb7946def0b321f1][section_title]" id="sections_cd2f2759895b5ae6cb7946def0b321f1_section_title">
<textarea rows="3" name="sections[cd2f2759895b5ae6cb7946def0b321f1][content]" id="sections_cd2f2759895b5ae6cb7946def0b321f1_content" cols="40">Bar1</textarea>

How do I force rails to always use the new resource behavior and not automatically add the id to the name and value. Do I have to create a custom form builder? Is there some other trick I can do to prevent rails from putting the id of the guide in there? I have tried a bunch of stuff and nothing is working.

Thanks in advance!

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about ruby-on-rails3