|
| 1 | +class CommentsController < ApplicationController |
| 2 | + before_action :authenticate_user! |
| 3 | + before_action :load_story_and_project |
| 4 | + before_action :find_comment, only: [:edit, :update, :destroy] |
| 5 | + |
| 6 | + def edit |
| 7 | + end |
| 8 | + |
| 9 | + def create |
| 10 | + @comment = current_user.comments.build(story: @story) |
| 11 | + @comment.attributes = comment_params |
| 12 | + saved = @comment.save |
| 13 | + if saved |
| 14 | + flash[:success] = "Comment created!" |
| 15 | + else |
| 16 | + flash[:error] = @comment.errors.full_messages |
| 17 | + end |
| 18 | + |
| 19 | + redirect_to project_story_path(@comment.story.project_id, @comment.story_id) |
| 20 | + end |
| 21 | + |
| 22 | + def update |
| 23 | + updated = @comment.update(comment_params) |
| 24 | + if updated |
| 25 | + flash[:success] = "Comment updated!" |
| 26 | + redirect_to project_story_path(@comment.story.project_id, @comment.story_id) |
| 27 | + else |
| 28 | + flash[:error] = @comment.errors.full_messages |
| 29 | + render :edit |
| 30 | + end |
| 31 | + end |
| 32 | + |
| 33 | + def destroy |
| 34 | + @comment.destroy |
| 35 | + flash[:success] = "Comment deleted!" |
| 36 | + redirect_to project_story_path(@comment.story.project_id, @comment.story_id) |
| 37 | + end |
| 38 | + |
| 39 | + private |
| 40 | + |
| 41 | + def find_comment |
| 42 | + @comment = current_user.comments.where(story_id: params[:story_id]).find(params[:id]) |
| 43 | + rescue ActiveRecord::RecordNotFound |
| 44 | + flash[:error] = "Comment not found" |
| 45 | + redirect_to project_story_path(params[:project_id], params[:story_id]) |
| 46 | + end |
| 47 | + |
| 48 | + def load_story_and_project |
| 49 | + @project = Project.find(params[:project_id]) |
| 50 | + @story = Story.find(params[:story_id]) |
| 51 | + rescue ActiveRecord::RecordNotFound |
| 52 | + flash[:error] = "Project or Story not found" |
| 53 | + redirect_to projects_path |
| 54 | + end |
| 55 | + |
| 56 | + def comment_params |
| 57 | + params.require(:comment).permit(:body) |
| 58 | + end |
| 59 | +end |
0 commit comments