From a8aa2c4f80c38e73cabdc261cc03f77f7014da03 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Fri, 11 Apr 2025 16:49:55 +0200 Subject: [PATCH] Clean up the controller --- app/controllers/cards/comments_controller.rb | 29 ++++++++------------ app/models/card/messages.rb | 6 ++++ 2 files changed, 18 insertions(+), 17 deletions(-) diff --git a/app/controllers/cards/comments_controller.rb b/app/controllers/cards/comments_controller.rb index 4f1745602..58e9f956b 100644 --- a/app/controllers/cards/comments_controller.rb +++ b/app/controllers/cards/comments_controller.rb @@ -1,10 +1,11 @@ class Cards::CommentsController < ApplicationController include CardScoped - before_action :set_comment, only: [ :show, :edit, :update, :destroy ] - before_action :require_own_comment, only: [ :edit, :update, :destroy ] + + before_action :set_comment, only: %i[ show edit update destroy ] + before_action :ensure_authorship, only: %i[ edit update destroy ] def create - @card.capture new_comment + @card.capture Comment.new(comment_params) end def show @@ -23,21 +24,15 @@ class Cards::CommentsController < ApplicationController end private + def set_comment + @comment = @card.comments.find(params[:id]) + end + + def ensure_authorship + head :forbidden if Current.user != @comment.creator + end + def comment_params params.require(:comment).permit(:body) end - - def new_comment - Comment.new(comment_params) - end - - def set_comment - @comment = Comment.joins(:message) - .where(messages: { card_id: @card.id }) - .find(params[:id]) - end - - def require_own_comment - head :forbidden unless Current.user == @comment.creator - end end diff --git a/app/models/card/messages.rb b/app/models/card/messages.rb index 01446905c..f77dd9fd1 100644 --- a/app/models/card/messages.rb +++ b/app/models/card/messages.rb @@ -3,9 +3,15 @@ module Card::Messages included do has_many :messages, -> { chronologically }, dependent: :destroy + has_many :comments, through: :messages, source: :messageable after_save :capture_draft_comment end + def comments + # FIXME: I could have sworn there was a way to declare this as a association? + Comment.joins(:message).where(messages: { card_id: id }) + end + def capture(messageable) messages.create! messageable: messageable end