2012-11-21 74 views
1

我正在使用Bootstrap-Sass以及Formstatic。我想到了一个错误信息会自动显示在这张照片旁边的Formstatic领域,如:here http://asciicasts.com/system/photos/227/original/E185I06.pngRails:表单验证错误未显示(使用Formtastic和Bootstrap-Sass)

但是,即使用户将输入无效,我的应用程序不显示错误消息。这似乎是一个简单的问题,但我无法弄清楚背后的原因。

PostController中

# POST /posts 
# POST /posts.json 
def create 
    @post = Post.new(params[:post]) 
    @post.view = 0 
    @post.like = 0 
    @post.hate = 0 
    respond_to do |format| 
    if @post.save 
     @posts = Post.paginate(:page => params[:page], order: 'like desc', per_page: 10) 
     format.html { redirect_to posts_path } 
     format.json { render json: @post, status: :created, location: @post } 
    else 
     format.html { render action: "new" } 
     format.json { render json: @post.errors, status: :unprocessable_entity } 
    end 
    end 
end 

PostModel

validates :name, :presence => true 
    validates :content, :presence => true, 
         :length => { :minimum => 10, :maximum => 300} 

_form(POST)

<% @post = Post.new %> 
<%= semantic_form_for @post do |f| %> 
<%= f.semantic_errors :name %> 
<%= f.inputs do %> 
    <%= f.input :name, :label => 'name' %> 
    <%= f.input :content, :label => 'body' %> 
<% end %> 
<%= f.actions do %> 
    <%= f.action :submit, :button_html => { :class => "btn btn-primary" }, :as => :button %> 
    <%= f.action :cancel, :as => :link %> 
<% end %> 

在PostController中,我试图删除以下两行

#format.html { render action: "new" } 
    #format.json { render json: @post.errors, status: :unprocessable_entity } 

,并添加

render @post.errors 

然后,我得到了

@messages={:name=>["can't be blank"], :content=>["can't be blank", "is too short (minimum is 10 characters)"]}> 

所以我觉得这个问题可能是我的方式m渲染json是错误的。有人可以帮我解决这个问题吗?

回答

0

Rails有自己的验证错误渲染,它与Bootstrap使用的HTML结构或CSS结构不匹配。

要解决这个问题,您可以添加查看您自己的代码块输出错误。

<% if @posts and @posts.errors and @posts.errors.count > 0 %> 
<div class="alert alert-danger"> 
    <a class="close" data-dismiss="alert">&times;<a> 
    <strong><%= pluralize(@posts.errors.count,"error") %> validation problems found.</strong> 
    <ul> 
    <% @posts.errors.full_messages.each do |error| %> 
    <li><%= error %></li> 
    <% end %> 
    </ul> 
</div> 

或者你可以将此块移动到部分模板,以避免代码dublication。

<% if resource and resource.errors and resource.errors.count > 0 %> 
    <div class="alert alert-danger"> 
    <a class="close" data-dismiss="alert">&times;<a> 
    <strong><%= pluralize(resource.errors.count,"error") %> validation problems found.</strong> 
    <ul> 
    <% resource.errors.full_messages.each do |error| %> 
     <li><%= error %></li> 
    <% end %> 
    </ul> 
    </div> 
<% end %> 

又通到@posts参数

<%= render "shared/validation_errors", :resource => @posts %> 

在这里你可以找到关于这个问题 http://fizzylogic.nl/2013/12/22/temp-slug-54/

更多信息