Question

I've got a controller method that reads like this:

def new_edits
  @document = Document.find(params[:id])
  @document.publications.each { |p| p.build_edit(body: p.component.body, name: p.component.name, publication_id: p.id) }
end

And a matching form with this structure:

<%= form_for(@document.publications, url: url_for(create_edits_document_path)) do |f| %>
  <%= f.fields_for :edit do |ef| %>
    <%= ef.text_field(:name) %>
    <%= ef.text_area(:body, class: 'editable_area') %>
    <%= ef.hidden_field(:publication_id) %>
  <% end %>
<% end %>

I can only seem to build one instance of the fields_for when there should be three. A Document has many Components through Publications (and vice versa), and a Publication can have up to one Edit. Any thoughts? Thanks.

Was it helpful?

Solution

Your whole approach look wrong to me. Fields for has only one instance because a publication can have only upto one edit. I think you should define it like this.

<%= form_for(@document, url: url_for(create_edits_document_path)) do |f| %>
  <%= f.fields_for :publications do |pub| %>
    <%= pub.fields_for :edit, pub.object.edit do |ef| %>
      <%= ef.text_field(:name) %>
      <%= ef.text_area(:body, class: 'editable_area') %>
      <%= ef.hidden_field(:publication_id) %>
    <% end %>
  <% end %>
<% end %>

You might find some issues as the above code is not tested.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top