lib/readymade/form.rb in readymade-0.2.4 vs lib/readymade/form.rb in readymade-0.2.5
- old
+ new
@@ -43,10 +43,12 @@
def permitted_attributes
@permitted_attributes ||= self.class::PERMITTED_ATTRIBUTES
end
def required_attributes
+ return [] if params.try(:[], :_destroy).present?
+
@required_attributes ||= self.class::REQUIRED_ATTRIBUTES
end
def build_nested_forms
nested_forms_mapping.each do |attr, form_class|
@@ -77,24 +79,32 @@
nested_forms.compact.map(&:validate).all? || sync_nested_errors(nested_forms)
end
# copy errors from nested forms into parent form
def sync_nested_errors(nested_forms)
- nested_forms.each do |n_form|
- n_form.errors.each do |code, text|
- errors.add("#{n_form.humanized_name}.#{code}", text)
+ if rails_errors_v2?
+ nested_forms.each do |n_form|
+ n_form.errors.each do |code|
+ errors.add("#{n_form.humanized_name}.#{code.attribute}", code.message)
+ end
end
+ else
+ nested_forms.each do |n_form|
+ n_form.errors.each do |code, text|
+ errors.add("#{n_form.humanized_name}.#{code}", text)
+ end
+ end
end
false
end
# sync errors from form to record or vice-versa
def sync_errors(from: self, to: record)
return if [from, to].any?(&:blank?)
- if Rails.version.to_f > 6.0
+ if rails_errors_v2?
from.errors.messages.each do |key, values|
Array.wrap(values).uniq.each do |uv|
to.errors.add(key, uv)
end
end
@@ -141,9 +151,15 @@
# define nested forms in format { attr_name: MyFormClass }
# use the following syntax if attribute is a collection: { attr_collection_name: [MyFormClass] }
def nested_forms_mapping
{}
+ end
+
+ private
+
+ def rails_errors_v2?
+ Rails.version.to_f > 6.0
end
# EXAMPLE
# class Items::Forms::Create::Value < ::Readymade::Form
# PERMITTED_ATTRIBUTES = %i[vat_percent price_type item_category].freeze