如何为field_for子表单中的字段设置error_message_on

时间:2010-08-30 02:15:33

标签: ruby-on-rails

我与使用fields_for操作嵌套的子表单有一对多的关系。

我想使用内置rails错误处理来使用error_message_on方法在子项上显示错误消息。

示例:

      <% form_for @business, :url => {:action => :page, :page => @page}, :html => {:method => :put } do |f| -%>
        <h5><strong>More Details</strong></h5>
        <div class="clear"></div>
        <div class="col-1">
          <label for="hours">Hours</label>
          <table class="hours">
            <tbody>
              <% f.fields_for :hours do |hours_form| %>
              <tr>
                <td><%= hours_form.label :day, hours_form.object.day %>:<%= hours_form.hidden_field :day %></td>
                <td><%= hours_form.text_field :open_time, :class => 'input' %></td>
                <td>to</td>
                <td><%= hours_form.text_field :close_time, :class => 'input' %></td>
                <td><%= hours_form.check_box :closed %></td>
                <td class="c6"><%= hours_form.label :closed, 'Closed this day' %>
                <%= hours_form.error_message_on :open_time, :css_class => 'cant-be-blank' %>
                <%= hours_form.error_message_on :close_time, :css_class => 'cant-be-blank' %></td>
              </tr>
              <% end -%>
            </tbody>
          </table>
...

1 个答案:

答案 0 :(得分:2)

您是否尝试f.error_messages显示商家错误和儿童时段表单,请使用hours_form.error_messages

例如

     <% form_for @business, :url => {:action => :page, :page => @page}, :html => {:method => :put } do |f| -%>
        <%= f.error_messages %>
        <h5><strong>More Details</strong></h5>
        <div class="clear"></div>
        <div class="col-1">
          <label for="hours">Hours</label>
          <table class="hours">
            <tbody>
              <% f.fields_for :hours do |hours_form| %>
              <%= hours_form.error_messages %>
              <tr>
                <td><%= hours_form.label :day, hours_form.object.day %>:<%= hours_form.hidden_field :day %></td>
                <td><%= hours_form.text_field :open_time, :class => 'input' %></td>
                <td>to</td>
                <td><%= hours_form.text_field :close_time, :class => 'input' %></td>
                <td><%= hours_form.check_box :closed %></td>
                <td class="c6"><%= hours_form.label :closed, 'Closed this day' %>
                <%= hours_form.error_message_on :open_time, :css_class => 'cant-be-blank' %>
                <%= hours_form.error_message_on :close_time, :css_class => 'cant-be-blank' %></td>
              </tr>
              <% end -%>
            </tbody>
          </table>