aboutsummaryrefslogtreecommitdiff
path: root/app/controllers/comments_controller.rb
blob: c4b21cb51d6102f996513c52659ebe23aa1f4261 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# frozen_string_literal: true

class CommentsController < ApplicationController
  include Taggable

  before_action :set_thing
  before_action :set_comment, only: %i[update destroy]

  def create
    ps = comment_params
    from = ps.delete(:from)
    tag_ids = ps.delete(:tag_ids)

    ok = ActiveRecord::Base.transaction do
      comment = @thing.comments.create(ps)
      next unless comment

      update_tags!(object: comment, ids: tag_ids)
    end

    flash[:alert] = t('comments.bad-create') unless ok
    handle_from_param!(from:)
  end

  def update
    ps = comment_params
    from = ps.delete(:from)
    tag_ids = ps.delete(:tag_ids)

    ok = ActiveRecord::Base.transaction do
      next unless @comment.update(ps)

      update_tags!(object: @comment, ids: tag_ids)
    end

    flash[:alert] = t('comments.bad-update') unless ok
    handle_from_param!(from:)
  end

  def destroy
    comment = Comment.find(params.expect(:id))
    comment.destroy

    handle_from_param!(from: params[:from])
  end

  protected

  def comment_params
    params.required(:comment).permit(:content, :from, tag_ids: [])
  end

  def set_thing
    @thing = Thing.find(params.expect(:thing_id))
  end

  def set_comment
    @comment = Comment.find(params.expect(:id))
  end

  def handle_from_param!(from:)
    if from == 'things/edit'
      redirect_to edit_thing_path(@thing)
    else
      redirect_to @thing
    end
  end
end