is there a way to render comments and replies inclusive of the user in ruby on rails

Viewed 22

I am working on a commenting system, where the comments and replies are on the same table, with replies having a reply_to column set to the id of the parent comment

class CreateComments < ActiveRecord::Migration[7.0]
  def change
    create_table :comments do |t|
      t.text :content
      t.references :user, null: false, foreign_key: true
      t.bigint :reply_to
      t.integer :upvote_count

      t.timestamps
    end
  end
end

In my comments_controller I have the following action and a helper function respectively to aid with querying the comments and replies inclusive of the user that created them.

class Api::CommentsController < ApplicationController
  before_action :authenticate_user!, only: [:create, :destroy]

  def index
    @comments = Comment.where(reply_to: nil).includes(:user).order(created_at: :desc)
    @comments = @comments.map do |comment|
      comment.as_json.merge(replies: get_replies(comment.id))
    end

    render json: @comments, include: :user, status: :ok
  end

  private

  # get all replies for a comment
  def get_replies(comment_id)
    Comment.where(reply_to: comment_id).includes(:user).order(created_at: :desc)
  end
end

With this query, I am only getting the user included in the replies but not the parent comment as shown below

[
    {
        "id": 1,
        "content": "hey this is a comment 1",
        "user_id": 2,
        "reply_to": null,
        "upvote_count": null,
        "created_at": "2022-09-06T19:00:38.996Z",
        "updated_at": "2022-09-06T19:00:38.996Z",
        "replies": [
            {
                "id": 3,
                "content": "hey this is a reply to comment 1",
                "user_id": 1,
                "reply_to": 1,
                "upvote_count": null,
                "created_at": "2022-09-06T19:07:53.729Z",
                "updated_at": "2022-09-06T19:07:53.729Z",
                "user": {
                    "id": 1,
                    "provider": "email",
                    "uid": "madmax@user.name",
                    "allow_password_change": false,
                    "avatar": "0",
                    "email": "madmax@user.name",
                    "created_at": "2022-09-06T18:18:02.558Z",
                    "updated_at": "2022-09-07T21:53:13.804Z"
                }
            }
        ]
    },
    {
        "id": 2,
        "content": "hey this is a comment comment 2",
        "user_id": 2,
        "reply_to": null,
        "upvote_count": null,
        "created_at": "2022-09-06T19:04:14.433Z",
        "updated_at": "2022-09-06T19:04:14.433Z",
        "replies": []
    }
]

My goal is to have the user included in both the parent comment and also the replies

0 Answers
Related