Start off with:
rails g resource comment post:references user:references content:text
Then
rails db:migrate
resources :posts do
resources :likes, only: [:create, :destroy]
resources :comments
end
In comments controller
class CommentsController < ApplicationController
def comment_params
params.require(:comment).permit(:content, :user_id)
end
def create
@post = Post.find(params[:post_id]) # Assuming you have a post object
# Create the comment and associate it with the current_user
@post.comments.create!(comment_params.merge(user: current_user))
redirect_to @post
end
end
In Post.rb
has_many :comments
In User.rb
has_many :comments
then create _comment.html.erbf
<div id="<%= dom_id(comment) %>">
<%= comment.content %>
<%= time_tag comment.updated_at, "data-local": "time-ago" %>
</div>
_comments.html.erb
<h2> Comments </h2>
<div id="comments">
<%= render post.comments %>
</div>
<%= render "comments/new", post: post %>
_new.html.erb
<%= form_with model: [ post, Comment.new ] do |f| %>
Your comment: <br>
<%= f.text_area :content, size: "20x5" %> <br>
<%= f.text_field :user_id, value: current_user.id, style: "display: none;" if current_user %>
<%= f.submit %>
<% end %>