Rails:表单验证错误未显示(使用Formtastic和Bootstrap-Sass)

时间:2012-11-21 04:03:41

标签: ruby-on-rails forms validation formtastic

我正在使用Bootstrap-Sass和Formstatic。我认为应该在Formstatic字段旁边自动显示一条错误消息,如下图所示:here http://asciicasts.com/system/photos/227/original/E185I06.png

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

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.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)"]}>

所以我认为问题可能是我渲染json的方式错了。有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

Rails有自己的验证错误渲染,它与HTML结构或Bootstrap使用的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>
   

或者您可以将此块移动到部分模板以避免出现代码。

<% 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/

相关问题