Question

My model Foo has_one :bar and Bar belongs_to :foo, and Foo accepts_nested_attributes_for :bar

When I create an instance of Foo (programatically, not via a form), I want to automatically create a blank child instance of Bar.

AFAIK I have to do it explicitly:

f = Foo.new(bar_attributes: {})
... do stuff ...
f.save

Is there an additional declaration in the model of Foo that says not only to accept nested attributes for bar, but to create one no matter what?

Was it helpful?

Solution

I would just use a callback in foo.rb

before_validation :init_foo, on: [ :create ]

def init_foo
   self.build_bar
end

This will create a new instance of bar linked to foo each time you create a new foo object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top