Skip to content

Instantly share code, notes, and snippets.

@sergii
Last active August 9, 2021 12:47
Show Gist options
  • Save sergii/fa0956450d9c6813d93723e4bc4d03f1 to your computer and use it in GitHub Desktop.
Save sergii/fa0956450d9c6813d93723e4bc4d03f1 to your computer and use it in GitHub Desktop.
How To Handle Special Actions In Ruby on Rails Controllers?
class Device < ApplicationRecord
# Define Validation Errors (TODO: Move it to a Validator)
class DeviceHasBeenAlreadySetUpError < StandartError
def message
"Device [#{@device.id}] has been already set up."
end
end
# => raise DeviceHasBeenAlreadySetUpError if @device.setup_at.present?
has_many :maintenances
end
class Maintenance < ApplicationRecord
# MaintenanceEntry - periodic process.
belongs_to :device
end
# Inspired by https://mikerogers.io/2021/03/19/how-to-handle-special-actions-in-ruby-on-rails-controllers
# Example 1
#
# app/controllers/devices/maintenance_controller.rb
class Devices::MaintenanceController < DevicesController
# DevicesController has a before_action for setting @device
# for the update method which we inherit.
# PATCH /devices/1/maintenance
def update
@device.touch(:maintained_at)
redirect_to device_path(@device)
end
end
# Example 2
#
# app/controllers/devices/maintenance_controller.rb
class Devices::MaintenanceController < DevicesController
# DevicesController has a before_action for setting @device
# for the update method which we inherit.
# GET /devices/1/maintenance/new
def new
# Do we really need that action?
# We generate all the things from QR code scanning.
end
# POST /devices/1/maintenances
def create
@device.maintenances.create(
ticket: params[:ticket], # SRV004
technician: params[:technician], # Jack Smitson
maintenance_type: params[:maintenance_type], # "planned" or "unplanned" or ....
# See more: https://en.wikipedia.org/wiki/Maintenance_(technical)
maintenance_start_at: Time.now.utc # 22.08.2008 14:30:00 UTC
)
redirect_to device_path(@device)
end
# PATCH /devices/1/maintenances/1
def update
@device.touch(:maintenance_end_at)
redirect_to device_path(@device)
end
end
# Inspired by https://mikerogers.io/2021/03/19/how-to-handle-special-actions-in-ruby-on-rails-controllers
# Example 1
#
# app/controllers/devices/setup_controller.rb
class Devices::SetupController < DevicesController
# DevicesController has a before_action for setting @device
# for the update method which we inherit.
# Note: We need the POST action as a Setup will happens only once.
# POST /devices/1/setup
def update
@device.touch(:setup_at)
redirect_to device_path(@device)
end
end
@sergii
Copy link
Author

sergii commented Aug 9, 2021

:qr_code_printed_at
:qr_code_linked_at

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment