我有以下两个_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
解决方法
只需添加错误: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 %>