簡體   English   中英

Rails:不顯示表單驗證錯誤(使用Formtastic和Bootstrap-Sass)

[英]Rails: Form Validation Errors Are Not Showing (with Formtastic and Bootstrap-Sass)

我正在將Bootstrap-Sass與Formstatic一起使用。 我認為應該使用Formstatic在該字段旁邊自動顯示錯誤消息,如下圖所示: 這里
(來源: asciicasts.com

但是,即使用戶輸入了無效的輸入,我的應用也不會顯示錯誤消息。 這似乎是一個簡單的問題,但我不知道背后的原因。

后控制器

# 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

后模型

  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的方式錯誤上。 有人可以幫我解決問題嗎?

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>

或者,您可以將此塊移至部分模板以避免代碼重復。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM