1
0
This repository has been archived on 2023-12-07. You can view files and clone it, but cannot push or open issues or pull requests.
body_tracking/app/models/measurement.rb
cryptogopher 681c0279fb Measurement improvements
Added 'new' action.
Separated js views for new/create/edit.
Displaying taken_at in local time.
Fixed readout destruction on edit.
2019-12-06 21:48:06 +01:00

49 lines
1.3 KiB
Ruby

class Measurement < ActiveRecord::Base
belongs_to :project, required: true
belongs_to :source, required: false
has_many :readouts, inverse_of: :measurement, dependent: :destroy, validate: true
validates :readouts, presence: true
accepts_nested_attributes_for :readouts, allow_destroy: true, reject_if: proc { |attrs|
attrs['quantity_id'].blank? && attrs['value'].blank?
}
# Readout quantity_id + unit_id uniqueness validation. Cannot be effectively
# checked on Readout model level.
validate do
quantities = self.readouts.map do |r|
[r.quantity_id, r.unit_id] unless r.marked_for_destruction?
end
if quantities.length != quantities.uniq.length
errors.add(:readouts, :duplicated_quantity_unit_pair)
end
end
validates :name, presence: true
validates :taken_at, presence: true
after_initialize do
if new_record?
self.hidden = false if self.hidden.nil?
self.taken_at = Time.now
end
end
def toggle_hidden!
self.toggle!(:hidden)
end
def taken_at_date
self.taken_at.getlocal
end
def taken_at_date=(value)
self.taken_at = Time.parse(value, self.taken_at)
end
def taken_at_time
self.taken_at.getlocal
end
def taken_at_time=(value)
self.taken_at = Time.parse(value, self.taken_at)
end
end