An alternative to the ActiveRecord after_initialize callback
I was playing with dynamic nested forms with Stimulus today and I stumbled upon a void left by Rails’ ActiveRecord callbacks.
I have this Caregiver model 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 Caregiver model:
# ceragiver.rb
def init_with_user
self.build_user
self
end
Then I just need to call it in my view like this:
<%= f.fields_for :caregivers, caregiver.new.init_with_user, 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.