Q:

rails controllers/forms - where to build nested models?

In my Rails app, I have a few forms that accept nested models for new objects.  So for example:
class Maker < ActiveRecord::Base
  has_many :cars
  accepts_nested_attributes_for :cars
end

class Car < ActiveRecord::Base
  belongs_to :maker
end

Before I show that form though, I need to build some of the nested models for my Maker model, or they don't show in the form.  E.g.:
maker = Maker.new
3.times do
  maker.cars.build
end

But where should this code ideally go?  In the model as its own form_display function, in the controller, in a decorator, etc.?

A:

Answers to this question will be somewhat opinion-based. From a separation-of-concerns standpoint, if you're already using decorators in your project it might make more sense to put the logic there than in the controller or the model.
# maker_decorator.rb
def cars
  if object.new_record? && object.cars.none?
    3.times { object.cars.build }
  end

  object.cars
end

If you don't want to deal with decorators, putting the logic in the controller seems a reasonable approach (as long as it's not being duplicated across multiple actions).
# makers_controller.rb
def new
  @maker = Maker.new
  3.times { @maker.cars.build }
end

I wouldn't add model code to handle this functionality since that's a rather blatant mixing of model and view concerns, though any use of accepts_nested_attributes_for will tend to push you down that route. "Form objects" avert this problem, though that might be a heavyweight solution in your case and there are few established libraries or conventions for this pattern at the moment (see #3 in this blog post).

