Search code examples
ruby-on-railsnested-form-for

Bates' nested_form with nested resource doesn't name new fields properly


I'm building a stackoverflow clone now, and trying to implement multiple file uploads on question and answer creation.

I'm using carrierwave with nested_form gem.

File upload on question creation works fine, but i can't make it work for answers. Here's my form for new answer:

= nested_form_for [@question, @answer], remote: true do |f|
    = render 'shared/error_messages', object: f.object
    div.form-group
      = f.label :body
      = f.text_area :body, class: 'form-control'
    div.form-group
      = f.fields_for :attachments do |field|
        = field.label :file
        = field.file_field :file
        = field.link_to_remove "Remove this attachment"
      p
        = f.link_to_add "Moar files!", :attachments
    div.form-group
      = f.submit 'Post answer', class: 'btn btn-primary'

It works OK when I'm trying to upload single file. The name of nested file_field goes like this:

name="answer[attachments_attributes][0][file]"

But when I click on 'Moar files' and another file field appears, it happens to be named

name="question[attachments_attributes][1429430703012][file]"

And thus in params I get second file tied to question, not the answer. And since request is being handled by answers_controller, second file is just being ignored.

How can I make nested_form_for name new field properly?

UPD

So I've tried to explicitly state parent object for attachments like this:

= f.fields_for :attachments, @answer.attachments do |field|

Still no luck


Solution

  • Turns out this is an old issue with nested_form, when it's being used more than one time on a page for two different objects with same polymorphic association.

    Here data-blueprint-id conflict on Nested form for polymorphic associations is another question describing same issue. Hope it will help someone.