Callback hell

I was playing with dynamic nested forms with Stimulus today and I stumbled upon a void left by Rails’ ActiveRecord callbacks.

I have this Caregivermodel within a nested form and I need to create it along with a User entity in my form, to be able to populate the fields. The problem is that creating an after_initialize callback (even with :new_record? will break the general behaviour of my app, and I don’t want to run through all the specs and fix FactoryBot issues etc.

So I just decided to create a small method in my Person model:

# ceragiver.rb

def init_with_user

Then I just need to call it in my view like this:

<%= f.fields_for :caregivers,, child_index: 'TEMPLATE_RECORD' do |cf| %>
  <%= render 'caregiver_fields', cf: cf %>
<% end %>

This makes the code in my view simpler, more explicit, while avoiding the dreaded callback hell.