2013-10-03 61 views
2

您好我有嵌套資源:導軌4示出在視圖中的錯誤消息驗證

resources :posts do 
    resources :msgs 
end 

和一些驗證:

class Msg < ActiveRecord::Base 
    belongs_to :post 
    validates :body ,presence:true 
end 

控制器:

# msgs_controller.erb 
def create 
@post = Post.find(params[:post_id]) 
@[email protected](msg_params) 
@msg.user=current_user 
@msg.email=current_user.email 
@msg.autor=current_user.name 

if @msg.save 
    flash[:notice] = t '.create' 
end 
respond_with(@post,@msg) 
end 

和一個視圖: EDIIT:/views/posts/show.html.rb #/views/show.html.erb

<h2>Add a comment:</h2> 
<%= form_for([@post, @post.msgs.build]) do |f| %> 

    <% if @msg.errors.any? %> 
     <div id="error_explanation"> 

      <h2><%= pluralize(@msg.errors.count, "error") %> prohibited this msg from being saved:</h2> 

      <ul> 
      <% @msg.errors.full_messages.each do |msg| %> 
       <li><%= msg %></li> 
      <% end %> 
      </ul> 
     </div> 
    <% end %> 


    <p> 
     <%= f.label :body %><br /> 
     <%= f.text_area :body %> 
    </p> 
    <p> 
     <%= f.submit %> 
    </p> 
<% end %> 

當body字段爲空時,應用程序不顯示錯誤消息,但驗證結果正常,因爲服務器顯示ROLLBACK而不是COMMIT。問題是在視圖中顯示錯誤消息,你能幫助我嗎?

+0

有什麼都在'@ msg.errors'?在你試圖保存的時候,@ msg'中的數據實際上是什麼樣的?你提到它正在做一個ROLLBACK,但如果驗證確實失敗了,它根本不會嘗試執行INSERT。請參閱http://edgeguides.rubyonrails.org/active_record_validations.html#presence - 第1.2節第二段。這表明驗證可能並不真正失敗,並且保存中的其他內容出錯(導致ROLLBACK)。 –

+0

您的'Posts'模型是否有'accep_nested_attributes_for:msg'?如果是這樣,我想知道這些錯誤是否會出現在@ post.errors中。也許試試看吧。 – lurker

+0

我已嘗試消除msg模型中的驗證,並在db中提交blanck註釋。驗證激活時,blanck註釋不會被提交,但會被回滾。我已經在服務器的日誌和數據庫查詢中看到了這一點。 – user1066183

回答

0

該表格應該在new而不是在show視圖中。然後,您可以渲染頁面,如果不保存顯示錯誤。

.... 
if @msg.save 
    flash[:notice] = t '.create' 
else 
    render 'new' 
end 
.... 
+0

是根據這篇文章http://archives.ryandaigle.com/articles/2009/8/10/what-s-new-in-edge-rails-default-restful-rendering respond_with方法響應與新的如果窗體有錯誤。所以我爲msg創建了一個新視圖,現在表單在這裏重定向(如果有錯誤),否則表單將重定向到post資源的顯示。 – user1066183

+0

在你的問題中,窗體出現在'show'視圖中,而不是按照推薦的'new'。如果你看看這篇文章,你會發現'create'有一個'if'和'else'的條件。 'else'(如果沒有保存)必須渲染表單,然後'@ msg.errors.any?'將會是'true',並顯示錯誤。如果你沒有保存時​​使用REDIRECT,你將不會有'@ msg.errors' .... – gabrielhilal

+0

好的謝謝,現在我已經完全理解了這個行爲。我的問題是我應該重定向錯誤不在:新,但在節目中.. – user1066183

1

退房這篇文章怎麼辦提示信息鋼軌4路:http://blog.remarkablelabs.com/2012/12/register-your-own-flash-types-rails-4-countdown-to-2013

從文章:

# app/controllers/application_controller.rb 
class ApplicationController 
    ... 
    add_flash_types :error, :another_custom_type 
end 

# app/controllers/users_controller.rb 
class UsersController < ApplicationController 
    def create 
    ... 
    redirect_to home_path, 
     error: "An error message for the user" 
    end 
end 

# app/views/home/index 
<%= error %>