DEV: Enforce dominant_color length in validation (#18309)

The `add_column` `limit` parameter has no effect on a postgres `text` column. Instead we can perform the check in ActiveRecord.

We never expect this condition to be hit - users cannot control this value. It's just a safety net.
This commit is contained in:
David Taylor 2022-09-21 11:01:21 +01:00 committed by GitHub
parent c73ca74585
commit 0f5a8cc526
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 19 additions and 1 deletions

View File

@ -37,6 +37,7 @@ class Upload < ActiveRecord::Base
validates_presence_of :filesize
validates_presence_of :original_filename
validates :dominant_color, length: { is: 6 }, allow_blank: true, allow_nil: true
validates_with UploadValidator

View File

@ -2,7 +2,7 @@
class AddDominantColorToUploads < ActiveRecord::Migration[7.0]
def change
add_column :uploads, :dominant_color, :text, limit: 6, null: true
add_column :uploads, :dominant_color, :text, null: true
add_index :uploads, :id, where: "dominant_color IS NULL"
end
end

View File

@ -689,5 +689,22 @@ RSpec.describe Upload do
expect(invalid_image.dominant_color).to eq(nil)
end
it "is validated for length" do
u = Fabricate(:upload)
# Acceptable values
u.update!(dominant_color: nil)
u.update!(dominant_color: "")
u.update!(dominant_color: "abcdef")
expect {
u.update!(dominant_color: "toomanycharacters")
}.to raise_error(ActiveRecord::RecordInvalid)
expect {
u.update!(dominant_color: "abcd")
}.to raise_error(ActiveRecord::RecordInvalid)
end
end
end