0

我正在尝试在 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">&times;</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">&times;</button>

评论当然属于可以有很多评论的帖子。有什么帮助吗?我尝试了我能想到的一切(因为我是 RoR 的新手,所以这并不多;) - 包括尝试获取错误消息的各种方法(@post.comment.errors.any? 等)。

提前致谢。蒂莫

4

1 回答 1

1

从您的评论来看,这里发生了很多事情。

您正在尝试创建评论,因此表单操作应该是 CommentsController#create。该视图是有意义的,它将是 PostsController#show(您没有指定),并且在渲染之前您需要实例化 @comment。可能:

帖子控制器

def show
  @post = Post.find(params[:id])
  @comment = @post.comments.build
end

评论控制器

def create
  @post = Post.find(params[:post_id])
  @comment = @post.comments.build(params[:comment].permit(:commenter, :body))
  if @comment.save
    redirect_to post_path(@post)
  else
    render :file => "posts/show"
  end 
end

请注意,您必须呈现而不是重定向,以便保留 @comment 实例并可以呈现错误。

帖子/show.html.erb

<%= form_for([@post, @post.comments.build], html: {class: 'form-horizontal'}) do |f| %>
    <% if @comment.errors.any? %>

这是否正确取决于您的 routes.rb。我假设评论是帖子中的嵌套资源,这就是您的问题导致的想法。

于 2013-08-19T20:36:32.103 回答