2012-03-30 79 views
0

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

檢查每個字段,並把錯誤元素中包含的每個字段:

<% if @product.errors.on(:title).present? %> 
    <span style="color:RED">WRITE YOUR ERROR MESSAGE</span> 
<% end %>