A memorandum of implementation of the comment function for posts.
--Manage comments in the Comment table (intermediate table) linked to the User table and Post table. --The Coment table has comment contents, commented post_id, and comment poster user_id columns. -(Premise) Use devise for the user function.
--Create comment model and table (comment content, comment contributor)
Terminal
% rails g model Comment comment_text:text user:references post:references
% rails g controller Comments
% rails db:migrate
Added association to model.
Comment model
belongs_to :post # Comment.Get commented posts on post
belongs_to :user # Comment.Get comment contributor with user
User model
has_many :posts, dependent: :destroy
has_many :comments, dependent: :destroy # User.Get user comments with comments
validates :comment_text, presence: true, length: { maximum: 1000 } #Validate the sky, limit the number of characters, etc. ..
Post model
belongs_to :user
has_many :comments, dependent: :destroy # Post.Get comments for that post with comments
Details page
-#Comment display
= @comments.each do |c|
= c.user.name
- if c.user.id == @post.user.id #Article contributor
%p Posted by
= simple_format(c.comment_text) #Display with line breaks
= link_to 'Delete', post_comment_path(@post, c), data: {confirm: '本当にDeleteしますか?'}, method: :delete
-#To delete a comment,@post (parent), @Must be passed to c in comments
-#Post a comment
= form_for [@post, @comment], local: true do |f| #Since comment is linked to post, write it as an array
= f.text_area :comment_test
= f.submit "Post"
Set the routing so that it is linked to the list display page.
routes.rb
resources :posts do #Nest to link to posts
resources :comments, only: [:create, :destroy]
end
Comment registration / deletion action (create / destroy).
Terminal
% rails g controller comments
comments controller
before_action :set_post
before_action :authenticate_user! #Allowed only while logged in
def create
@comment = @post.comments.create(comment_params)
if @comment.save
redirect_to blog_path(@post) notice: 'Commented'
else
flash.now[:alert] = 'Comment failed'
render post_path(@post)
end
end
def destroy
@comment = Comment.find(params[:id])
if @comment.destroy
redirect_to post_path(@post), notice: 'Deleted comment'
else
flash.now[:alert] = 'Failed to delete comment'
render post_path(@post)
end
end
private
def set_post
@post = Post.find(params[:post_id])
end
def comment_params
params.required(:comment).permit(:comment_text).merge(user_id: current_user.id, post_id: params[:post_id])
end
Since the comment list is also displayed on the post page (show), comment data can be obtained with posts # show.
posts controller
:
def show
@post = Post.find(params[:id])
@comment = Comment.new #Instantiate for a form(For adding comments)
@comments = @post.comments #For comment list display
end
:
Recommended Posts