17

我有以下两种_forms:

用户表单

<%= simple_form_for(@user, :url => @target) do |f| %>
  <% if @user.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:</h2>
      <ul>
      <% @user.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <%= f.input :email, :label => "User Email" %>
  <%= f.input :password, :label => "User Password" %>
  <%= f.input :first_name %>
  <%= f.input :last_name %>
  <%= f.button :submit %>
<% end %>

租户表格

<%= simple_form_for(@tenant, :url => @target) do |f| %>
  <% if @tenant.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@tenant.errors.count, "error") %> prohibited this tenant from being saved:</h2>

      <ul>
      <% @tenant.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <%= f.input :name, :label => 'Name', :required => true %>
  <%= f.input :billing_email, :label => 'Email', :required => true %>
  <%= f.input :country, :label => 'Country', :required => true %>
  <%= f.button :submit %>
<% end %>

我从Rails 3.0 中的 stackoverflow f.error_messages 中看到以下帖子

这里有一种方法,可以使用 f.error_messages 从简单的表单中返回错误消息,但我无法使其正常工作,因为我不确定该方法应该保存在哪里。有人有任何提示吗?方法如下:

class StandardBuilder < ActionView::Helpers::FormBuilder
  def error_messages
    return unless object.respond_to?(:errors) && object.errors.any?

    errors_list = ""
    errors_list << @template.content_tag(:span, "There are errors!", :class => "title-error")
    errors_list << object.errors.full_messages.map { |message| @template.content_tag(:li, message) }.join("\n")

    @template.content_tag(:ul, errors_list.html_safe, :class => "error-recap round-border")
  end
end
4

1 回答 1

24

只需将 error: false 添加到您的输入中,这不会清除 CSS,但会清除内联错误

f.input error: false or :error => false

编辑:

来自http://ruby.railstutorial.org/book/ruby-on-rails-tutorial

/app/views/shared/_error_messages.html.erb

 <% if object.errors.any? %>
  <div id="error_explanation">
   <div class="alert alert-error">
     The form contains <%= pluralize(object.errors.count, "error") %>.
   </div>
  <ul>
   <% object.errors.full_messages.each do |msg| %>
    <li>* <%= msg %></li>
   <% end %>
 </ul>
</div>
<% end %>

在视图中

<%= form_for(@user) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>

  <%= f.label :name %>
  <%= f.text_field :name %>

  <%= f.label :email %>
  <%= f.text_field :email %>

  <%= f.label :password %>
  <%= f.password_field :password %>

  <%= f.label :password_confirmation, "Confirmation" %>
  <%= f.password_field :password_confirmation %>

  <%= f.submit "Create my account", class: "btn btn-large btn-primary" %>
<% end %>
于 2013-02-01T20:40:20.173 回答