切换表单和注释顺序后,评论无效

时间:2017-03-24 19:10:24

标签: ruby-on-rails

将引导程序导入我的Rails博客项目后,我正在尝试设置我的评论。当@Comments出现在表格之前时,他们才开始工作。

<!-- Post Content -->
                <%= raw(@post.body) %>
                <%= render @post.comments %>

                <hr>

                <!-- Blog Comments -->

                <!-- Comments Form -->
                <div class="well">
                    <% if user_signed_in? %>
                        <h4>Leave a Comment:</h4>
                        <%= render 'comments/form' %>
                    <% end %>
                </div>

                <hr>

但是当评论放在我想要的地方时:

<!-- Post Content -->
                <%= raw(@post.body) %>


                <hr>

                <!-- Blog Comments -->

                <!-- Comments Form -->
                <div class="well">
                    <% if user_signed_in? %>
                        <h4>Leave a Comment:</h4>
                        <%= render 'comments/form' %>
                    <% end %>
                </div>

                <hr>

                <!-- Posted Comments -->


                <!-- Comment -->
                <%= render @post.comments %>

我得到一个未定义的方法错误:&#34;未定义的方法`别名&#39;为零:NilClass&#34;。它似乎无法读取传递给一个方法的对象。为了获得别名,我调用了comment.user.alias。如果我只使用comment.user,它会工作,但它会返回一个对象哈希。

_form.html.erb

<%= form_for([@post,@post.comments.build]) do |f| %>
<div class="form-group">
    <%= f.text_area :body, :class => "form-control", :rows => 3 %>
</div>
<%= f.submit :class => "btn btn-primary" %>
<% end %>

_comment.html.erb

<div class="media">
    <div class="media-body">
        <% if comment.user == current_user %>
            <%= link_to 'X',[comment.post,comment], method: :delete, data: { confirm: 'Are you sure?' }, class: "delete-button" %>
        <% end %>
        <h4 class="media-heading"><%= comment.user.alias %>
            <small><%= comment.created_at.strftime("Created on %m/%d/%Y") %></small>
        </h4>
        <%= comment.body %>
    </div>
</div>

评论控制器

class CommentsController < ApplicationController

    def create
        @post = Post.find(params[:post_id])
        @comment = @post.comments.create(params[:comment].permit(:body))
        @comment.user_id = current_user.id
        @comment.save
        redirect_to post_path(@post)
    end

    def destroy
        @post = Post.find(params[:post_id])
        @comment = @post.comments.find(params[:id])
        if @comment.user_id == current_user.id
        @comment.destroy
        redirect_to post_path(@post)
        end

    end
end

0 个答案:

没有答案