RBOnRails-learning/app/controllers/comments_controller.rb

32 lines
828 B
Ruby
Raw Normal View History

2024-08-07 14:43:33 +00:00
class CommentsController < ApplicationController
2024-08-08 09:19:44 +00:00
before_action :require_user
2024-08-07 14:43:33 +00:00
def create
@article = Article.find(params[:article_id])
2024-08-08 09:19:44 +00:00
@comment = @article.comments.new(comment_params)
@comment.commenter = current_user.username
if @comment.save
flash[:notice] = "Comment added successfully."
else
flash[:alert] = "Failed to add comment."
end
2024-08-07 14:43:33 +00:00
redirect_to article_path(@article)
end
def destroy
@article = Article.find(params[:article_id])
@comment = @article.comments.find(params[:id])
2024-08-08 09:19:44 +00:00
if @article.user_id == current_user.id || @comment.commenter == current_user.username
@comment.destroy
end
2024-08-07 14:43:33 +00:00
redirect_to article_path(@article), status: :see_other
end
private
def comment_params
2024-08-08 09:19:44 +00:00
params.require(:comment).permit(:body, :status)
2024-08-07 14:43:33 +00:00
end
end