0

When using a form that contains nested resources it is necessary to ensure that the nested resources exist for the form builder to work appropriately.

I have seen this achieved in numerous ways – building them in the controller or building them in the view, but I have never seen a consistent approach.

If a form contains nested has_one items, where should those items be built if they don't already exist on the model?

Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
Undistraction
  • 42,754
  • 56
  • 195
  • 331

1 Answers1

1

Generally you're right. People use everything everywhere. The question is - is it a good practice? Does it affect another developers?

In my opinion, as you're using MVC pattern, view is a description of how you'll serve some content for user. So that, building, fetching, creating etc. is a controller job. Besides that, your code should be as clear as it's possible for another developer. Otherwise it becomes inconsistent, because logic is splitted between controller and view.

In this case, that's the preffered way:

#model:
has_one :item

#controller:
def new
  # ...
  something.build_item if something.item.blank?
  # ...
end
blelump
  • 3,233
  • 1
  • 16
  • 20