Validate Unit base user

This commit is contained in:
cryptogopher 2024-04-02 22:20:45 +02:00
parent 1966c782bc
commit a5a75233c7
2 changed files with 9 additions and 4 deletions

View File

@ -1,17 +1,17 @@
class Unit < ApplicationRecord
belongs_to :user, optional: true
# TODO: validate base.user == user
belongs_to :base, optional: true, class_name: "Unit"
has_many :subunits, class_name: "Unit", dependent: :restrict_with_error, inverse_of: :base
validate if: ->{ base.present? } do
errors.add(:base, :user_mismatch) unless user == base.user
errors.add(:base, :multilevel_nesting) if base.base.present?
end
validates :symbol, presence: true, uniqueness: {scope: :user_id},
length: {maximum: columns_hash['symbol'].limit}
validates :name, length: {maximum: columns_hash['name'].limit}
validates :multiplier, numericality: {equal_to: 1}, unless: :base
validates :multiplier, numericality: {other_than: 0}, if: :base
validate if: ->{ base&.base.present? } do
errors.add(:base, :multilevel_nesting)
end
scope :defaults, ->{ where(user: nil) }
scope :ordered, ->{

View File

@ -17,6 +17,11 @@ en:
models:
unit:
attributes:
base:
multilevel_nesting: has to be a top-level unit
user_mismatch: has to belong to the same user as unit
multiplier:
equal_to: for a top-level unit has to be 1
symbol:
taken: has to be unique
actioncontroller: