【发布时间】:2013-10-03 15:19:34
【问题描述】:
嗨,我有嵌套资源:
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])
@msg=@post.msgs.build(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
还有一个观点: 编辑:/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 %>
当正文字段为空时,应用程序不会显示错误消息,但验证正常,因为服务器显示 ROLLBACK 而不是 COMMIT。问题是在视图中显示错误消息,你能帮帮我吗?
【问题讨论】:
-
@msg.errors有什么东西吗?当您尝试保存时,@msg中的数据实际上是什么样的?您提到它正在执行 ROLLBACK,但如果验证确实失败,它根本不会尝试执行 INSERT。请参阅edgeguides.rubyonrails.org/… - 第 1.2 节,第二段。这表明可能验证实际上并没有失败,并且保存时出现了其他问题(导致 ROLLBACK)。 -
您的
Posts模型是否有accepts_nested_attributes_for :msg?如果是这样,我想知道错误是否会出现在@post.errors中。也许试试看。 -
我试图消除 msg 模型中的验证,并且在数据库中提交了空白注释。在验证活动的情况下,空白注释不会被提交,而是被回滚。我在服务器的日志和数据库查询中看到了这一点。
标签: ruby-on-rails validation form-for