我有以下两个_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 %>
我在stackoverflow f.error_messages in Rails 3.0
中遇到了以下帖子这里有方法,因此可以使用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
答案 0 :(得分:24)
只需在输入中添加错误: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 %>
在VIEW中
<%= 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 %>