Nested Forms
Added in 2.1.0
Matestack provides functionality for reactive nested forms.
This works in conjunction with rails' accepts_nested_attributes_for. From the rails documentation on nested attributes:
Nested attributes allow you to save attributes on associated records through the parent. By default nested attribute updating is turned off and you can enable it using the accepts_nested_attributes_for class method. When you enable nested attributes an attribute writer is defined on the model.
There is a little bit of setup required to enable this. There's a need for accepts_nested_attributes_for, index_errors on a models' has_many associations and an ActiveRecord patch.
Consider the following model setup, which is the same model found in the dummy app in the spec directory (active in this dummy app):
class DummyModel < ApplicationRecord
validates :title, presence: true, uniqueness: true
has_many :dummy_child_models, index_errors: true
accepts_nested_attributes_for :dummy_child_models, allow_destroy: true
end
class DummyChildModel < ApplicationRecord
validates :title, presence: true, uniqueness: true
endIndex Errors
Note the has_many :dummy_child_models, index_errors: true declaration in the Dummy Model declaration above.
Normally with rails, when rendering forms using Active Record models, errors are available on individual model instances. When using accepts_nested_attributes_for, error messages sent as JSON are not as useful because it is not possible to figure out which associated model object the error relates to.
From rails 5, we can add an index to errors on nested models. We can add the option index_errors: true to has_many association to enable this behaviour on individual association.
ActiveRecord Patch
Matestack nested forms support requires an ActiveRecord patch. This is because index_errors does not consider indexes of the correct existing sub records.
See rails issue #24390
Add this monkey patch to your rails app
Controller Setup
Adjusting strong params for nested form support does not differ from what needs to be done when using classsic Rails forms, e.g.:
Example
Dynamically Adding Nested Items (Optional)
As in the example above, you can dynamically add nested items. As the comment in the code suggests type: :button is important, otherwise form submission may be triggered when removing an item.
Dynamically Removing Nested Items (Optional)
As in the example above, as well as dynamically adding items, you can dynamically remove nested items. Again, important: type: :button is important, otherwise form submission may be triggered when adding an item.
Last updated