开发者

fields_for in table produces technically incorrect HTML

开发者 https://www.devze.com 2023-03-17 15:30 出处:网络
When I use a construct like: <table> <%= f.fields_for :group_locations do |gl| %> <tr>

When I use a construct like:

<table>
    <%= f.fields_for :group_locations do |gl| %>
        <tr>
            <td><%= gl.label :group_id %></td>
            <td><%= gl.select :group_id, paths %></td>
        </tr>
    <% end %>
</table>

I get an error in my browser (Safari) for each row in the table (<input> is not allowed inside <tbody>. Inserting <input> before the <table> inst开发者_如何学Cead.) This is caused by the hidden <input> for the association's id being placed after the </tr>. How can I cause the id's <input> to appear inside one of the TD elements?


I think the hidden field won't be printed if you print it manually. Could you try this?

<table>
    <tr>
        <%= f.fields_for :group_locations do |gl| %>
            <td><%= gl.hidden_field :id %></td>
            <td><%= gl.label :group_id %></td>
            <td><%= gl.select :group_id, paths %></td>
        <% end %>
    </tr>
</table>


The fields_for method concatenates the hidden id <input> to the end of the block it captures. So, if you put your <% end %> tag before your second </td>, you should get the result you want.


This is more of a comment (but I don't seem to be able to comment directly). Just wanted to note that Dogbert's answer worked for me. The malformed html didn't seem to worry most browsers... until I tried to use jquery ui sortable on the the table in IE8, which caused a number of problems (including a crash). Anyway, explicitly including the id in a hidden field inside a td seems the way to go. You may want to consider only doing this if the object is persisted (otherwise the hidden field has no value, which may or may not be an issue depending on your code). Adding a check to see if an object is persisted might look like (in the above case):

<% if gl.object.persisted? %>
  <td><%= gl.hidden_field :id %></td>
<% end %>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号