This project is archived and is in readonly mode.

#3259 ✓resolved
Will Read

Allow explicit placement of hidden fields with nested models

Reported by Will Read | September 25th, 2009 @ 09:40 PM | in 2.x

When using fields_for to build DOM structure for nested models, the id hidden field gets emitted implicitly and the developer has not control over the placement which can result in invalid HTML. As an example:

class Foo < ActiveRecord::Base
  has_many :bars
  accepts_nested_attributes_for :bars
end

and the template

<% form_for @foo do |foo_form| %> 
<table> 
  <tbody> 
    <% foo_form.fields_for :bars do |bar_fields| %> 
      <tr> 
        <td><%= bar_fields.text_field :name %></td> 
      </tr> 
    <% end %> 
  </tbody> 
</table> 
<% end %>

The hidden input gets placed at the point of the call to fields_for, right after the TBODY, which results in invalid HTML. The consequence is that some browsers, eg. Safari, try to fix the generated HTML for you, resulting in an inconsistent DOM structure across browsers.

I added a method, #hidden_fields, to FormBuilder to explicitly place the hidden fields. If this methods gets called in the #fields_for block the FormBuilder won't implicitly emit the hidden fields.

For example:

<% form_for @foo do |foo_form| %> 
<table> 
  <tbody> 
    <% foo_form.fields_for :bars do |bar_fields| %> 
      <tr>
        <%= bar_fields.hidden_fields %> 
        <td><%= bar_fields.text_field :name %></td> 
      </tr> 
    <% end %> 
  </tbody> 
</table> 
<% end %>

I've attached a patch with the new functionality, including tests.

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

Referenced by

Pages