我在Rails博客上显示评论时遇到问题

时间:2019-01-23 05:07:08

标签: html ruby-on-rails blogs ruby-on-rails-5.2

我目前正在我的Rails博客上工作。尽管进展顺利,但我在评论中遇到了障碍。

每次尝试留下测试注释时,总是会在保存注释之前得到“回滚事务”。 Here's what happens when I create a comment.

以下是查看博客条目的代码:

post / show.html.erb

<h1 class="title">
  <%= @post.title %>
</h1>
<h2>Authored by:
  <%= @post.user.username%>
</h2>
<p>
  <%=raw @post.content %>
</p>

<div class="comments">
  <h3 class="is-3">Comments</h3>

  <%if  @post.comments.count == 0%>
    <strong>There are no comments on this post. Feel free to send one!</strong><br/>
    <% else %>
      <%= render @post.comments %>
        <% end %>

          <%if !user_signed_in? %>
            <strong>Yo, if you wanna comment on my site, either <%= link_to 'Sign up',  new_user_registration_path %> or <%= link_to 'Log in',  new_user_session_path %></strong>
            <% else %>
              <%= render partial: "comments/form", locals: {comment: @post.comments.new} %>
                <% end %>
</div>
</div>
<br>
<% if user_signed_in? %>
  <div class="functions">
    <%= link_to "Update", edit_post_path(@post) if policy(@post).update? do%>
      <i class="fa fa-edit editpage fa-3x"></i>
      <% end %>
        <%= link_to "Delete", @post, :confirm => "Are you sure you want to delete this post?", :method => :delete  if policy(@post).destroy? do%>
          <i class="fa fa-trash deletepage fa-3x"></i>
          <% end %>
  </div>
  <% end %>
    <%= link_to 'Back to the main page', root_path %>

如果您感到好奇,这是部分注释的样子:

<strong><%= @post.comment.user.username %> says:</strong><br>
<%=@post.comment.content %>
  <p>
    <=time_ago_in_words(comment.created_at) %>
</p>

任何人都可以帮助我弄清楚为什么当我创建评论时会回滚交易吗?如果需要,我将提供更多信息。

编辑:这是我的rails博客的Comments Controller。

class CommentsController < ApplicationController
    before_action :set_post
    def create
        set_post
        # Create associated model, just like we did in the console before
        @comment = @post.comments.create(comment_params)
        # We want to show the comment in the context of the Post
        @comment.post_id = @post.post_id
        @comment.user_id = current_user.user_id
        @comment.save
        redirect_to @post
    end


    def update
        @comment = set_comment
        @comment.update(comment_params)
        redirect_to @post
    end

    def destroy
        @comment = set_comment
        @comment.destroy
        redirect_to @post
    end

    private
    def comment_params
        params.require(:comment).permit(:content)
    end

    def set_post
        @post = Post.friendly.find(params[:post_id])
    end

    def set_comment
        @comment = Comment.find(params[:id])
    end
end


评论模型:

class Comment < ApplicationRecord
    belongs_to :post
    belongs_to :user
end

还有评论表单

<strong><%= @post.comment.user.username %> says:</strong><br>
    <%=@post.comment.content %>
    <p><= time_ago_in_words(comment.created_at) %></p>

0 个答案:

没有答案