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

Web Dev

Render's Support

I'm really happy with Render's support and will be recommending them for people to consider

Web dev

Free tools to improve your website

There are lots of freely available tools to help get a sense check on how your website is doing and recommend improvements