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

Ruby

Forcing a Rails database column to be not null

How you can force a table column to always have something in it with Rails

Writing Marketing

We've deleted an article's worth of unhelpful words

We've improved several pages across our site by removing words that add no value, and often detract from the article.