Alex Rivera | Logout

Proper way to initialize nested fields in Rails forms

Asked 2011-12-09T23:43:45.900
8

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?

Edit
Report

1 Answer

0

i believe that build_address is already built in for rails after u declare a has_one association, so you don't need to write that bit urself. and if the form is called only from the new action, what u really need is only the controller bit, and nothing else

answered 2011-12-09T23:52:45.567

Your Answer