Skip to content

Models without error hash generate undefined method '[]' for nil:NilClass #24

Open
@tjdavey

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.

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions