Description
Valid form elements generate undefined method '[]' for nil:NilClass
when the form's model does not include an errors
hash.
There are some scenarios when rails forms models are not set from an ActiveRecord model. In these scenarios, unless they emulate the errors
hash produced by ActiveRecord, the rendering of the form element will result in the aforementioned error.
Example:
<%= bootstrap_form_with(model: my_model) do |f| %>
<%= f.text_field :top_level_field %>
<%= f.fields_for :nested_hash, OpenStruct.new(my_model.nested_hash) do |ff| %>
<%= ff.text_field :nested_hash_field %>
<% end %>
<%= f.primary "Save" %>
<% end %>
In this scenario, with vanilla rails form elements, OpenStruct provides all the necessary methods for the nested_hash_field
property to be rendered correctly. Using comfy-bootstrap-form
this will generate an error unless the nested_hash
includes an errors
property.
Suggested Fix
The draw_errors
method in form_builder.rb
already includes a fast-return path if the model is nil
. The criteria should this should be expanded to also return if the errors
hash is not present.