您好我有嵌套资源:导轨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