我正在尝试在 Rails 中实现错误消息,但不知何故无法让它在某一时刻工作。
我正在尝试添加错误消息的视图:
<%= form_for([@post, @post.comments.build], html: {class: 'form-horizontal'}) do |f| %>
<% if @comment.errors.any? %>
<div id="errorExplanation" class="span5 offset1 alert alert-error">
<button type="button" class="close" data-dismiss="alert">×</button>
<h4>Something went wrong!</h4><br>
<% @post.errors.full_messages.each do |msg| %>
<p><%= msg %></p>
<% end %>
</div>
<% end %>
和控制器:
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(params[:comment].permit(:commenter, :body))
redirect_to post_path(@post)
end
和错误信息:
nil 的未定义方法“错误”:NilClass 提取的源代码(在 #65 行附近):
<li>
<%= form_for([@post, @post.comments.build], html: {class: 'form-horizontal'}) do |f| %>
65 -> <% if @comment.errors.any? %>
<div id="errorExplanation" class="span5 offset1 alert alert-error">
<button type="button" class="close" data-dismiss="alert">×</button>
评论当然属于可以有很多评论的帖子。有什么帮助吗?我尝试了我能想到的一切(因为我是 RoR 的新手,所以这并不多;) - 包括尝试获取错误消息的各种方法(@post.comment.errors.any? 等)。
提前致谢。蒂莫