mirror of
https://github.com/discourse/discourse.git
synced 2025-02-25 18:55:32 -06:00
DEV: Set limits on custom fields
This patch sets some limits on custom fields: - an entity can’t have more than 100 custom fields defined on it - a custom field can’t hold a value greater than 10,000,000 characters The current implementation of custom fields is relatively complex and does an upsert in SQL at some point, thus preventing to simply add an `ActiveRecord` validation on the custom field model without having to rewrite a part of the existing logic. That’s one of the reasons this patch is implementing validations in the `HasCustomField` module adding them to the model including the module.
This commit is contained in:
committed by
Loïc Guitaut
parent
c08a52e502
commit
5257c80064
@@ -60,12 +60,19 @@ module HasCustomFields
|
||||
end
|
||||
end
|
||||
|
||||
included do
|
||||
has_many :_custom_fields, dependent: :destroy, class_name: "#{name}CustomField"
|
||||
after_save :save_custom_fields
|
||||
CUSTOM_FIELDS_MAX_ITEMS = 100
|
||||
CUSTOM_FIELDS_MAX_VALUE_LENGTH = 10_000_000
|
||||
|
||||
included do
|
||||
attr_reader :preloaded_custom_fields
|
||||
|
||||
has_many :_custom_fields, dependent: :destroy, class_name: "#{name}CustomField"
|
||||
|
||||
validate :custom_fields_max_items, unless: :custom_fields_clean?
|
||||
validate :custom_fields_value_length, unless: :custom_fields_clean?
|
||||
|
||||
after_save :save_custom_fields
|
||||
|
||||
def custom_fields_fk
|
||||
@custom_fields_fk ||= "#{_custom_fields.reflect_on_all_associations(:belongs_to)[0].name}_id"
|
||||
end
|
||||
@@ -133,6 +140,28 @@ module HasCustomFields
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def custom_fields_max_items
|
||||
if custom_fields.size > CUSTOM_FIELDS_MAX_ITEMS
|
||||
errors.add(
|
||||
:base,
|
||||
I18n.t("custom_fields.validations.max_items", max_items_number: CUSTOM_FIELDS_MAX_ITEMS),
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
def custom_fields_value_length
|
||||
return if custom_fields.values.all? { _1.to_s.size <= CUSTOM_FIELDS_MAX_VALUE_LENGTH }
|
||||
errors.add(
|
||||
:base,
|
||||
I18n.t(
|
||||
"custom_fields.validations.max_value_length",
|
||||
max_value_length: CUSTOM_FIELDS_MAX_VALUE_LENGTH,
|
||||
),
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
def reload(options = nil)
|
||||
|
||||
Reference in New Issue
Block a user