Search code examples
ruby-on-railsformsfields-for

Rails rendering fields_for for a model that multiple has_many relationships


I have a model components which belongs to a main container model. The components model has many servers and services. Basically all is fine, except it renders out two of each from because in my controller I set up the fields_for with this code:

@reference.components.build.servers.build
@reference.components.build.services.build

So it is clear why I am getting multiple forms, Is there a way to build the has_many relationships on one line? I have tried:

@reference.components.build.servers.build.services.build

and

1.times { @reference.components.build.servers.build }
1.times { @reference.components.build.services.build }

Thank you

UPDATE ->

Moving the code into a block seems to work (I was just guessing)

@reference.components.build do |f|
  f.servers.build
  f.services.build
end

That code is in the controller.


Solution

  • The key thing is to only call components.build once, or else you'll be adding one component per call to build

    For example

    component = @reference.components.build
    component.servers.build
    component.services.build
    

    should work fine. The block form you've stumbled on achieves the same thing (I have a feeling that that was only added in 3.2, possibly one of the minor releases after 3.2)