2

ネストされたコメントを作成しています (Reddit で見られるように)。親コメントを作成することはできますが、子コメントを作成しようとすると、単に親コメントとしてレンダリングされます。

私の Rails コンソールでは、「ancestry」フィールドが「nil」に戻ります。

これは私のコメントコントローラーです:

class CommentsController < ApplicationController
  before_action :set_comment, only: [:show, :edit, :update, :destroy]
  before_filter :authenticate_user!

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

  def new
    @link = Link.find(params[:link_id])
    @comment = Comment.new(:parent_id => params[:parent_id])
    @comments = Comment.all
  end

  def create
    @link = Link.find(params[:link_id])

    @parent = Link.find(params[:link_id]) if params[:link_id]
    @parent = Comment.find(params[:comment_id]) if params[:comment_id]

    @comment = @parent.comments.new(comment_params)
    @comment.user = current_user

    respond_to do |format|
      if @comment.save
        format.html { redirect_to @link, notice: 'Comment was successfully created.' }
        format.json { render json: @comment, status: :created, location: @comment }
      else
        format.html { render action: "new" }
        format.json { render json: @comment.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @comment.destroy
    respond_to do |format|
      format.html { redirect_to :back, notice: 'Comment was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private

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


    def comment_params
      params.require(:comment).permit(:link_id, :body, :user_id)
    end
end

ここに私の _comment_form 部分があります

<%= div_for(comment) do %>
    <div class="comments_wrapper clearfix">
        <div class="pull-left">
            <p class="lead"><%= comment.body %></p>
            <p><small>Submitted <strong><%= time_ago_in_words(comment.created_at) %> ago</strong> by <%= comment.user.email %></small></p>
                    <div id="reply" style="display:none;">
                <%= form_for [@comment = Comment.new(:parent_id => params[:parent_id])] do |f| %>
                <%= f.hidden_field :parent_id %>
                  <%= f.text_area :body %> <br>
                  <%= f.submit %>
                  <% end %>
                </div>
        </div>

        <div class="actions btn-group pull-right">
            <button onClick="$('#reply').show()" class="btn btn-sm btn-default">Reply</button>

            <% if comment.user == current_user -%>
                <%= link_to 'Destroy', comment, method: :delete, data: { confirm: 'Are you sure?' }, class: "btn btn-sm btn-default" %>
            <% end %>
        </div>
    </div>

<% end %>

これらは私のルートです

Rails.application.routes.draw do
  resources :comments
  devise_for :users
  devise_for :installs
  resources :links do
    member do 
      put "like", to: "links#upvote"
      put "dislike", to: "links#downvote"
    end
    resources :comments
  end

  root to: "links#index"
end
4

1 に答える 1