Antoine
Antoine

Reputation: 5245

Initialize child models at model creation

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.

Upvotes: 2

Views: 496

Answers (2)

Harish Shetty
Harish Shetty

Reputation: 64363

You can't register a call back method for after_initialize event. You have to implement a method called after_initialize.

Try this:

class Vin < ActiveRecord::Base
  def after_initialize
    self.producteur = Producteur.new if new_record?
  end
end

Upvotes: 0

Dave Isaacs
Dave Isaacs

Reputation: 4539

You probably need

def vin_setup
  self.producteur = Producteur.new
end

The way you have it, you are initializing a local variable named producteur.

Upvotes: 1

Related Questions