Created
December 23, 2016 16:34
-
-
Save vakiliy/79065395469e507efde0107a715b61cf to your computer and use it in GitHub Desktop.
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 CreateTimeInStates < ActiveRecord::Migration[5.0] | |
def up | |
execute <<-SQL | |
CREATE TYPE state_trackable_models AS ENUM ('AutoProcess', 'Partner'); | |
SQL | |
create_table :time_in_states do |t| | |
t.integer :state, null: false | |
t.column :state_trackable_id, :integer, null: false | |
t.column :state_trackable_type, :state_trackable_models, null: false | |
t.datetime :begin_at, null: false | |
t.datetime :end_at | |
end | |
add_index :time_in_states, [:state_trackable_type, :state_trackable_id], name: 'time_in_state_trackable_index' | |
end | |
end | |
class TimeInState < ApplicationRecord | |
belongs_to :state_trackable, polymorphic: true | |
# Для вызова в цепочки | |
# пример: auto_process.time_in_state.track_state | |
def self.track_state | |
owner = all.proxy_association.owner | |
return false unless owner.present? | |
if owner.state != last&.state | |
current = Time.now | |
update(end_at: current) if last.present? | |
create(begin_at: current, state: owner.state) | |
end | |
end | |
end | |
class AutoProcess < ApplicationRecord | |
has_many :time_in_states, as: :state_trackable | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment