Module: NuecaRailsInterfaces::V3::FormInterface
- Defined in:
- lib/nueca_rails_interfaces/v3/form_interface.rb
Overview
V3 Form Interface delegates model validation to the actual model instances rather than reimplementing model validations inside the form.
Models managed by the form are declared explicitly with the ‘model` macro. Their attributes arrive as a nested hash keyed by the model name, which is what `fields_for :school_year, f.object.school_year` produces in the view; e.g. `school_year: { name: “…” }`. This maps directly to: `params.expect(my_form: [{ school_year: [:name] }, :other_field])`
Only models listed in the ‘model` macro are processed; any key whose name matches a declared model and whose value is a Hash (or Parameters) is treated as model attributes. Everything else is treated as a regular form attribute. Fields inside a model hash that the model does not recognise are silently discarded.
Custom form-level fields (fields that belong to the form, not to any model) are declared as plain ‘attr_accessor`s on the form class, just like any other ActiveModel attribute.
Calling ‘valid?` on the form runs form-level validations first, then calls `valid?` on each model instance and propagates any model errors onto the form under the model name key (e.g. `errors`). `fields_for :payment` in the view binds to `form.payment` and reads that object’s own errors for per-field error rendering, so both levels work naturally together.
The ‘attributes` method returns a hash of model instances merged with any regular form attributes. It can be overridden in the form class.
Defined Under Namespace
Modules: InstanceMethods
Class Method Summary collapse
Instance Method Summary collapse
-
#attributes ⇒ Object
Returns a merged hash of model instances and regular form attributes.
Class Method Details
.included(base) ⇒ Object
121 122 123 124 125 |
# File 'lib/nueca_rails_interfaces/v3/form_interface.rb', line 121 def included(base) base.include(ActiveModel::Model) base.prepend(InstanceMethods) define_class_macros(base) end |
Instance Method Details
#attributes ⇒ Object
Returns a merged hash of model instances and regular form attributes. Defined here (included, not prepended) so that a form class can override it by defining its own ‘attributes` method; the class-level definition is found first in the MRO, falling back to this default when no override exists.
158 159 160 161 162 163 |
# File 'lib/nueca_rails_interfaces/v3/form_interface.rb', line 158 def attributes result = {} result.merge!(@model_instances) result.merge!(@regular_attributes.transform_keys(&:to_sym)) result.with_indifferent_access end |