您好我有嵌套資源:導軌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。問題是在視圖中顯示錯誤消息,你能幫助我嗎?
有什麼都在'@ msg.errors'?在你試圖保存的時候,@ msg'中的數據實際上是什麼樣的?你提到它正在做一個ROLLBACK,但如果驗證確實失敗了,它根本不會嘗試執行INSERT。請參閱http://edgeguides.rubyonrails.org/active_record_validations.html#presence - 第1.2節第二段。這表明驗證可能並不真正失敗,並且保存中的其他內容出錯(導致ROLLBACK)。 –
您的'Posts'模型是否有'accep_nested_attributes_for:msg'?如果是這樣,我想知道這些錯誤是否會出現在@ post.errors中。也許試試看吧。 – lurker
我已嘗試消除msg模型中的驗證,並在db中提交blanck註釋。驗證激活時,blanck註釋不會被提交,但會被回滾。我已經在服務器的日誌和數據庫查詢中看到了這一點。 – user1066183