From 98c8fb9346cb80a3ce1f757ef144213dc8d51051 Mon Sep 17 00:00:00 2001 From: cryptogopher Date: Fri, 5 Jan 2024 21:32:59 +0100 Subject: [PATCH] Validate Unit string lengths --- app/models/unit.rb | 7 +++++-- app/views/units/_form.html.erb | 5 +++-- test/system/units_test.rb | 4 ++-- 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/app/models/unit.rb b/app/models/unit.rb index 4f50405..f466809 100644 --- a/app/models/unit.rb +++ b/app/models/unit.rb @@ -4,14 +4,17 @@ class Unit < ApplicationRecord belongs_to :user, optional: true belongs_to :base, optional: true, class_name: "Unit" - validates :symbol, presence: true, uniqueness: {scope: :user_id} + 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: 1}, if: :base validate if: -> { base.present? } do errors.add(:base, :only_top_level_base_units) unless base.base.nil? end - acts_as_nested_set parent_column: :base_id, scope: :user, dependent: :destroy, order_column: :multiplier + acts_as_nested_set parent_column: :base_id, scope: :user, dependent: :destroy, + order_column: :multiplier scope :defaults, -> { where(user: nil) } diff --git a/app/views/units/_form.html.erb b/app/views/units/_form.html.erb index 014a937..50a8cec 100644 --- a/app/views/units/_form.html.erb +++ b/app/views/units/_form.html.erb @@ -1,10 +1,11 @@ <%= fields_for unit do |form| %> <%= form.text_field :symbol, form: :unit_form, required: true, autofocus: true, size: 10, - autocomplete: "off" %> + maxlength: unit.class.columns_hash['symbol'].limit, autocomplete: "off" %> - <%= form.text_field :name, form: :unit_form, size: 25, autocomplete: "off" %> + <%= form.text_field :name, form: :unit_form, size: 25, + maxlength: unit.class.columns_hash['name'].limit, autocomplete: "off" %> <% unless unit.base.nil? %> diff --git a/test/system/units_test.rb b/test/system/units_test.rb index 2c4e676..4323d9c 100644 --- a/test/system/units_test.rb +++ b/test/system/units_test.rb @@ -18,8 +18,8 @@ class UnitsTest < ApplicationSystemTestCase within first('tbody > tr') do assert_selector ':focus' - fill_in 'unit[symbol]', with: SecureRandom.random_symbol(rand(1..10)) - fill_in 'unit[name]', with: [nil, SecureRandom.alphanumeric(rand(1..500))].sample + fill_in 'unit[symbol]', with: SecureRandom.random_symbol(rand(1..16)) + fill_in 'unit[name]', with: [nil, SecureRandom.alphanumeric(rand(1..255))].sample assert_difference ->{ Unit.count }, 1 do click_on t(:add) end