Ignore empty nested attributes when using Rails Admin

How to resolve issues that arise with saving models if you have empty nested attributes using reject_if

When using Rails Admin we use accepts_nested_attributes_for to give our clients a cleaner and less complicated view. They were recently having issues with saving an instance of a model with a field which was not required. On a little more digging we discovered that they created an empty instance of a nested rails model.

To resolve this we changed our accepts_nested_attributes_for to use reject_if:

accepts_nested_attributes_for :cover_image, allow_destroy: true, reject_if: proc { |attribute| attribute[:body].blank? }

This checks to see if the body attribute (which is required in the nested model) is blank and if so rejects it meaning that the parent model can save.

Recent posts View all

VS CodeWeb Dev

Select multiple lines in VS Code

How to select multiple lines to edit at once within VS Code

VS Code Web Dev

Move a line up or down with VS Code

A quick tip on moving lines up or down a file using your keyboard in VS Code