Rails – Nested forms and has_one relationship
I was trying to build a nested form with Rails 3.1, using models that had a “has_one” relationship. The form would show the parents fields but not the nested models field.
So I started by defining the has_one relationship in the models and adding “accepts_nested_attributes_for to the Parent :
class Parent < ActiveRecord::Base
has_one :child, :dependent => :destroy
accepts_nested_attributes_for :child
end
class Child < ActiveRecord::Base
belongs_to :parent
end
Just this wasn’t enough. The solution involves initializing the Child by the Parent. This can be done in the Controller or the Model.
In the Model:
class Parent < ActiveRecord::Base
has_one :child, :dependent => :destroy
accepts_nested_attributes_for :child
after_initialize do
self.child ||= self.build_child()
end
end
Or in the Controller:
class ParentsController < ApplicationController
def new
@parent = Parents.new
@parent.build_child
end
end
So, a question, where is the best place to initialize the Child? In the Parents Controller or Model?

No comments yet.