From fea736bd36946a8397114efe99884d64060495e0 Mon Sep 17 00:00:00 2001 From: cryptogopher Date: Fri, 16 Aug 2019 19:29:23 +0200 Subject: [PATCH] Changed Unit.type -> .group Added Unit validations. Added default Units. --- app/helpers/units_helper.rb | 6 +++--- app/models/unit.rb | 8 +++++++- app/views/units/_form.html.erb | 2 +- config/locales/en.yml | 2 +- db/migrate/001_create_units.rb | 15 ++++++++++++++- 5 files changed, 26 insertions(+), 7 deletions(-) diff --git a/app/helpers/units_helper.rb b/app/helpers/units_helper.rb index 0bda873..b1d9fe1 100644 --- a/app/helpers/units_helper.rb +++ b/app/helpers/units_helper.rb @@ -1,6 +1,6 @@ module UnitsHelper - def type_options - translations = t('.types') - Unit.types.map { |k,v| [translations[k.to_sym], k] } + def group_options + translations = t('.groups') + Unit.groups.map { |k,v| [translations[k.to_sym], k] } end end diff --git a/app/models/unit.rb b/app/models/unit.rb index c78467a..2a20bdf 100644 --- a/app/models/unit.rb +++ b/app/models/unit.rb @@ -1,6 +1,8 @@ class Unit < ActiveRecord::Base + belongs_to :project + # https://en.wikipedia.org/wiki/International_System_of_Units - enum type: { + enum group: { number: 0, share: 1, @@ -21,4 +23,8 @@ class Unit < ActiveRecord::Base pressure: 40 } + + validates :project, associated: true + validates :name, :shortname, presence: true + validates :group, inclusion: groups.keys end diff --git a/app/views/units/_form.html.erb b/app/views/units/_form.html.erb index 04ef794..87404dc 100644 --- a/app/views/units/_form.html.erb +++ b/app/views/units/_form.html.erb @@ -6,7 +6,7 @@

<%= f.text_field :shortname, required: true, size: 10 %>

-

<%= f.select :type, type_options, required: true %>

+

<%= f.select :group, group_options, required: true %>

<%= f.text_field :name, required: true, size: 40 %>

diff --git a/config/locales/en.yml b/config/locales/en.yml index 77e7e84..e6ddaee 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -15,7 +15,7 @@ en: heading: 'Units' heading_new_unit: 'New unit' form: - types: + groups: number: 'count' share: 'share' length: 'length' diff --git a/db/migrate/001_create_units.rb b/db/migrate/001_create_units.rb index 58ac06b..6a73d19 100644 --- a/db/migrate/001_create_units.rb +++ b/db/migrate/001_create_units.rb @@ -4,7 +4,20 @@ class CreateUnits < ActiveRecord::Migration t.references :project t.string :name t.string :shortname - t.integer :type + t.integer :group + end + + reversible do |dir| + dir.up do + Unit.create project: nil, shortname: "", name: "count", group: :number + Unit.create project: nil, shortname: "%", name: "percent", group: :share + Unit.create project: nil, shortname: "g", name: "gram", group: :mass + Unit.create project: nil, shortname: "kg", name: "kilogram", group: :mass + end + + dir.down do + Unit.delete_all + end end end end