Initialize child models at model creation
- by Antoine
I have a model Entree which belongs to a model Vin, which itself belongs to a model Producteur.
On the form for Entree creation/edition, I want to allow the user to define the attributes for parent Vin and Producteur to create them, or retrieve them if they exist (retrieval based on user input).
For now I do the following in Entree new and edit actions:
@entree = Entree.new
@entree.vin = Vin.new
@entree.vin.producteur = Producteur.new
and use fields_for helper in the form,and that works. But I intend to have much more dependencies with more models, so I want to keep it DRY. I defined a after_initialize callback in Vin model which does the producteur initialization:
class Vin < ActiveRecord::Base
after_initialize :vin_setup
def vin_setup
producteur = Producteur.new
end
end
and remove the producteur.new from the controller. However, get an error on new action:
undefined method `model_name' for NilClass:Class
for the line in the form that says
<%= fields_for @entree.vin.producteur do |producteur| %>
I guess that means the after_initialize callback doesn't act as I expect it. Is there something I'm missing? Also, I get the same error if I define a after_initialize method in the Vin model instead of definiing a callback.