Ruby on Rails field_for Form Helper Problems

I use the field_for form helper with a loop:

<% f.fields_for :permissions do |permission_form| %>
    <tr>
      <td><%= permission_form.object.security_module.name %><%= permission_form.hidden_field(:security_module_id) %></td>
      <td><%= permission_form.object.security_module.description %></td>
    <tr>
<% end %>

The result of the above code is as follows:

    <input id="role_permissions_attributes_0_id" name="role[permissions_attributes][0][id]" type="hidden" value="76" />
    <tr>
      <td>Diary<input id="role_permissions_attributes_0_security_module_id" name="role[permissions_attributes][0][security_module_id]" type="hidden" value="13" /></td>
       <td>Access to the Diary Module</td>
    </tr>
    <!-- next input field then <tr> tag -->

The problem with this markup is that the input tag goes beyond the tr tag, which there causes problems with validation with XHTML.

Does anyone know how I can get an input tag to fall inside the tr tag, thereby giving me valid XHTML 1.0 STRICT markup?

thanks

+3
source share
3 answers

If you look at the source code for Rails, you will find this.

# in actionpack/lib/action_view/helpers/form_helper.rb
def fields_for_nested_model(name, object, args, block)
  if object.new_record?
    @template.fields_for(name, object, *args, &block)
  else
    @template.fields_for(name, object, *args) do |builder|
      @template.concat builder.hidden_field(:id)
      block.call(builder)
    end
  end
end

Please note that a hidden field is added here, and it does not seem like there is any way to change this behavior. The easiest way is probably to create your own form builder.

# in lib/no_id_form_builder.rb
class NoIdFormBuilder < ActionView::Helpers::FormBuilder
  private
  def fields_for_nested_model(name, object, args, block)
    @template.fields_for(name, object, *args, &block)
  end
end

. id .

<% f.fields_for :permissions, :builder => NoIdFormBuilder do |permission_form| %>
  <tr>
    <td>
      <%= permission_form.object.security_module.name %>
      <%= permission_form.hidden_field(:security_module_id) %>
      <%= permission_form.hidden_field(:id) unless permission_form.object.new_record? %>
    </td>
    <td><%= permission_form.object.security_module.description %></td>
  <tr>
<% end %>

, . , fields_for :skip_id_field, .

+4

, 2.3.5. : id, :

<% form_for @foo do |f| %> 
<table> 
  <tbody> 
    <% f.fields_for :bars do |bf| %> 
      <tr>
        <td>
          <%= bf.hidden_field :id %>
          <%= bf.text_field :name %>
        </td> 
      </tr> 
    <% end %> 
  </tbody> 
</table> 
<% end %>

https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/3259

+2

Minor correction:

The: builder should go to form_for, which contains file_fields, not for_fields.

0
source

Source: https://habr.com/ru/post/1714451/


All Articles