Last active
October 1, 2019 09:12
-
-
Save rummelonp/8034712 to your computer and use it in GitHub Desktop.
ActiveRecord で Enumerize と StateMachine 使うやつ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Yokkyu < ActiveRecord::Base | |
extend Enumerize | |
enumerize :status, scope: true, default: :awaiting in: { | |
awaiting: 1, | |
approved: 2, | |
rejected: 3, | |
} | |
state_machine :status do | |
state :awaiting | |
state :approved | |
state :rejected | |
before_transition any => :approve, do: :set_approved_at | |
before_transition any => :rejected, do: :set_rejected_at | |
event :approve do | |
transition to: :approved, from: [:awaiting] | |
end | |
event :reject do | |
transition to: :rejected, from: [:awaiting, :approved] | |
end | |
end | |
def change_status(event) | |
event = event.to_sym | |
if event.in?(status_events) | |
send(event) | |
else | |
errors.add(:status, :invalid_transition) | |
false | |
end | |
end | |
private | |
def set_approved_at | |
self.approved_at = Time.now | |
end | |
def set_rejected_at | |
self.rejected_at = Time.now | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment