Rails默认在ul中显示表单上方的所有表单错误消息。我希望每个字段的错误消息显示在相应的字段旁边。
form.html.erb
<%= form_for @product do |f| %>
<% if @product.errors.any? %>
<ul id="error_explanation">
<% @product.errors.each_with_index do |msg, i| %>
<li><%= msg[1] %></li>
<% end %>
</ul>
<% end %>
<fieldset>
<%= f.text_field :title, :placeholder => "Product Title", :title => "Type product title", :autofocus => 'autofocus' %>
<%= f.text_area :description, :placeholder => "Product Description", :title => "Type product description" %>
<%= f.collection_select :category_id, Category.all, :id, :name %>
</fieldset>
<%= f.submit "Create", :class => "btn btn-big btn-action" %>
<%= link_to "cancel", categories_path %>
<% end %>
product.rb
class Product < ActiveRecord::Base
attr_accessible :title, :description, :price, :category_id
validates :title, :presence => { :message => "All products need a title bro!" }
validates_uniqueness_of :title
validates :description, :presence => { :message => "This ain't gonna be too interesting without a description?!" }
validates :price, :presence => { :message => "How you gonna make money if shit is free?!" }
belongs_to :category
end
答案 0 :(得分:0)
检查每个字段并将错误元素与每个字段放在一起,如:
<% if @product.errors.on(:title).present? %>
<span style="color:RED">WRITE YOUR ERROR MESSAGE</span>
<% end %>
答案 1 :(得分:0)
使用Formtastic,它会自动执行此操作。