【问题标题】:Add message to formtastic semantic error block将消息添加到格式语义错误块
【发布时间】:2012-02-28 20:15:15
【问题描述】:

如果表单中存在语义错误(主要来自外部 API),我想添加一条解释性消息,如下所示:

<%= semantic_form_for @order, :url => checkout_purchase_url, :html => {:class => 'payment'}, :wrapper_html => { :class => "field" }  do |f| %>
<% if f.has_errors? %>
    <p>There were errors that prevented your order from being submitted.  If you need assistance, please contact us toll-free at <strong>1-800-555-5555</strong>.</p>
    <%= f.semantic_errors %>
<% end %>
<% end %>

但是,has_errors? 是受保护的方法。有没有办法我可以做到这一点?谢谢。

【问题讨论】:

    标签: ruby-on-rails-3 formtastic


    【解决方案1】:

    如果您有嵌套属性,您将不会看到任何与它们相关的错误。确保您获得所有基本错误和任何嵌套属性错误。确保您的模型包含:

    validates_presence_of :nested_object
    validates_associated :nested_object
    

    并以您的形式:

    f.semantic_errors *f.object.errors.keys
    

    【讨论】:

      【解决方案2】:

      没有我想象的那么难。我通过检查对象而不是表单上的错误来修复它:

      <% if @object.errors.any? %>
          <p>There were errors that prevented your order from being submitted.  If you need assistance, please contact us toll-free at <strong>1-800-555-5555</strong>.</p>
          <%= f.semantic_errors %>
      <% end %>
      

      感谢观看的人。

      【讨论】:

        【解决方案3】:

        为了完整起见,如果您想在每个字段上显示类似的有用消息,这里有另一种方法:

        = f.label :title
        - if f.object.errors.any?
         .error = f.object.errors[:title].flatten.join(' and ')
        = f.text_field :title
        

        这为每个字段提供了格式精美且样式简单的错误列表。 (如果您愿意,可以使用 semantic_errors 而不是 object.errors,同样的结果。)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-11-06
          • 2011-02-06
          相关资源
          最近更新 更多