У меня проблемы с отображением комментариев в моем блоге Rails - PullRequest
0 голосов
/ 23 января 2019

Я сейчас работаю над своим блогом Rails.Хотя разработка идет хорошо, я столкнулся с препятствием в комментарии.

Каждый раз, когда я пытаюсь оставить тестовый комментарий, я всегда получаю «транзакцию отката» как раз перед сохранением комментария. Вот что происходит, когда я создаю комментарий.

Вот код для просмотра записи в блоге:

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.

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>

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...