Add basic functionality
This commit is contained in:
+22
-2
@@ -1,4 +1,24 @@
|
||||
class Admission < ApplicationRecord
|
||||
belongs_to :country
|
||||
belongs_to :person
|
||||
belongs_to :country, inverse_of: :admissions
|
||||
belongs_to :person, inverse_of: :admissions
|
||||
belongs_to :previous, class_name: name, inverse_of: :next, optional: true
|
||||
has_one :next, class_name: name, foreign_key: :previous_id, inverse_of: :previous
|
||||
|
||||
scope :ordered, -> { order(:arrived_on, :previous_id) }
|
||||
scope :before, -> (date) { where("#{table_name}.arrived_on <= ?", date) }
|
||||
scope :after, -> (date) { where("#{table_name}.arrived_on >= ?", date) }
|
||||
|
||||
around_create :set_previous
|
||||
before_destroy :update_nexts_previous
|
||||
|
||||
def set_previous
|
||||
self.previous ||= person.admissions.ordered.before(arrived_on).last
|
||||
future_next = previous&.reload_next
|
||||
yield
|
||||
future_next&.update(previous: self)
|
||||
end
|
||||
|
||||
def update_nexts_previous
|
||||
self.next&.update(previous: previous)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,2 +1,4 @@
|
||||
class Country < ApplicationRecord
|
||||
has_many :admissions, inverse_of: :country
|
||||
has_many :people, foreign_key: :birth_country_id, inverse_of: :birth_country
|
||||
end
|
||||
|
||||
@@ -1,2 +1,18 @@
|
||||
class Person < ApplicationRecord
|
||||
belongs_to :birth_country, class_name: Country.name
|
||||
has_many :admissions
|
||||
|
||||
def stays
|
||||
stays = []
|
||||
admissions.ordered.includes(:country).all.each_cons(2) do |a, b|
|
||||
stays.push(
|
||||
country: a.country,
|
||||
arrival: a.arrived_on,
|
||||
departure: b.arrived_on,
|
||||
duration: (b.arrived_on - a.arrived_on).to_i + 1
|
||||
)
|
||||
end
|
||||
|
||||
stays
|
||||
end
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user