-
-
Save nicedawg/0d6b6c3907175ed645cd6c1ebb2965c4 to your computer and use it in GitHub Desktop.
[Beginning Rails 6] Listing 9-10. The Comments Controller in app/controllers/comments_controller.rb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CommentsController < ApplicationController | |
before_action :load_article, except: :destroy | |
before_action :authenticate, only: :destroy | |
def create | |
@comment = @article.comments.new(comment_params) | |
if @comment.save | |
respond_to do |format| | |
format.html { redirect_to @article, notice: 'Thanks for your comment' } | |
format.js | |
end | |
else | |
respond_to do |format| | |
format.html { redirect_to @article, notice: 'Unable to add comment' } | |
format.js { render :fail_create } | |
end | |
end | |
end | |
def destroy | |
@article = current_user.articles.find(params[:article_id]) | |
@comment = @article.comments.find(params[:id]) | |
@comment.destroy | |
respond_to do |format| | |
format.html { redirect_to @article, notice: 'Comment deleted' } | |
format.js | |
end | |
end | |
private | |
def load_article | |
@article = Article.find(params[:article_id]) | |
end | |
def comment_params | |
params.require(:comment).permit(:name, :email, :body) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment