I'd like to understand what's the "proper" way to initialize the nested fields of a model.
Let's say you have some nested fields for a model:
class User
has_one :address
accepts_nested_attributes_for :address
end
And you need to initialize those attributes (address in this case) to use them in a fields_for call.
So far I've thought of three ways to do this.
First, after_initialize hook on the model:
class User
after_initialize :init_address
protected
def init_address
address ||= build_address
end
Then we have initialization in the controller:
class UsersController
def new
@user = User.new
@user.build_address
end
end
And finally, we can have a helper method to do it for us:
module FormHelpers
def setup_user(user)
user.address ||= user.build_address
user
end
end
# view
<%= form_for setup_user(@user)... %>
Is there anything resembling a standard or a "best practice" for this scenario? How do you do it and why?