Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to initialize nested fields in Rails forms

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?

like image 246
Federico Builes Avatar asked Dec 09 '11 23:12

Federico Builes


1 Answers

I think that if the nested attribute doesn't make sense at all without the parent model, building and initialization of these nested models should be the responsibility of the parent model.

I don't see why the UsersController should care about how the @user.addresses are built or initialized. For me, giving the controller this responsibility, would probably imply that on create he should be the one that parsed and built the nested attributes (which, happens in the model).

I would go for the first approach.

like image 166
Hock Avatar answered Nov 06 '22 23:11

Hock