如何在表单字段下方显示验证错误消息,而不是在页面顶部显示所有消息。
My Rails版本为 Rails 3.0.0
我有一个包含字段ID,标题和说明的表名类别。 我的模型类是
class Category < ActiveRecord::Base
validates_uniqueness_of :title, :message => "Title already exist"
validates_presence_of :title, :description => "Cannot be blank"
end
控制器
class CategoriesController < ApplicationController
def index
end
def new
end
def create
@category = Category.new(params[:category])
@category.created = Time.now
@category.modified = Time.now
respond_to do |format|
if @category.save
@category_last=Category.last
format.html { redirect_to :controller => 'categories', :action => 'show', :id => @category_last.id }
else
#format.html { redirect_to :controller => 'categories', :action => 'new' }
end
end
end
def show
end
def edit
end
end
和查看
<div id="newCategory" class='page add'>
<div class='screenTitle'>New Category</div>
<div class='form_wrapper'>
<%= form_tag :action=>'create' %>
<div class='field_wrapper'>
<div class='field_label'>
Title
</div>
<div class='field_input'>
<%= text_area(:category, :description, :class=>'') %>
</div>
<div class='clearfix'> </div>
</div>
<div class='field_wrapper'>
<div class='field_label'>
Title
</div>
<div class='field_input'>
<%= text_field(:category, :title, :class=>'') %>
</div>
<div class='clearfix'> </div>
</div>
<div class='field_wrapper'>
<div class='field_submit'>
<%= submit_tag "Submit", :type => "submit", :class => "submit" %>
</div>
<div class='clearfix'> </div>
</div>
</form>
</div>
<div class='actions'>
<ul>
<li><%= link_to 'List Categoris', root_url+'categories' %></li>
</ul>
<div class='clearfix'> </div>
</div>
</div>
答案 0 :(得分:2)
我可能会做这样的事情。在动作中使用空模型:new like like:
def new
@category = Category.new
end
然后使用form_for而不是form_tag,如下所示:
<%= form_for @category, :action=>'create' do |f| %>
<%= f.text_field(:title, :class=>'') %>
然后在动作中:创建我会尝试这个:
if @category.save
# redirect if you want to
else
render :action => :new
end
这样,如果由于某种原因创建失败,控制器将呈现模板:new但仍然使用form_for帮助器中失败的@category对象。您始终可以使用@ category.errors.on(:title)
访问模型的错误消息因此,请将以下内容添加到要显示错误消息的视图中:
<%= @category.errors.on(:title) unless @category.errors.on(:title).nil? %>
答案 1 :(得分:1)
您可能需要查看formtastic。那里有很多令人敬畏的东西,非常好地按字段做错误。