Class: RailsImagePostSolution::ImageReportsController

Inherits:
ApplicationController show all
Defined in:
app/controllers/rails_image_post_solution/image_reports_controller.rb

Instance Method Summary collapse

Methods inherited from ApplicationController

#default_url_options, #require_admin, #require_login

Instance Method Details

#createObject



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
# File 'app/controllers/rails_image_post_solution/image_reports_controller.rb', line 8

def create
  # Check if already reported
  existing_report = ImageReport.find_by(
    active_storage_attachment_id: @attachment.id,
    user_id: current_user.id
  )

  if existing_report
    respond_to do |format|
      format.json do
        render json: { error: I18n.t("rails_image_post_solution.flash.already_reported") },
               status: :unprocessable_entity
      end
      format.html do
        redirect_back fallback_location: root_path,
                      alert: I18n.t("rails_image_post_solution.flash.already_reported")
      end
    end
    return
  end

  @report = ImageReport.new(
    active_storage_attachment_id: @attachment.id,
    user_id: current_user.id,
    reason: params[:reason],
    status: ImageReport::STATUSES[:pending]
  )

  if @report.save
    # Run image moderation only on first report
    if ImageReport.where(active_storage_attachment_id: @attachment.id).count == 1
      ImageModerationJob.perform_later(@attachment.id)
    end

    respond_to do |format|
      format.json do
        render json: { success: true, message: I18n.t("rails_image_post_solution.flash.report_received") },
               status: :created
      end
      format.html do
        redirect_back fallback_location: root_path,
                      notice: I18n.t("rails_image_post_solution.flash.report_received")
      end
    end
  else
    respond_to do |format|
      format.json { render json: { error: @report.errors.full_messages.join(", ") }, status: :unprocessable_entity }
      format.html { redirect_back fallback_location: root_path, alert: @report.errors.full_messages.join(", ") }
    end
  end
end