ryanb / nested_form

Rails plugin to conveniently handle multiple models in a single form.
MIT License
1.79k stars 505 forks source link

file_field issues #275

Open napster3000 opened 11 years ago

napster3000 commented 11 years ago

class PlayerProfile < ActiveRecord::Base has_many :player_photos accepts_nested_attributes_for :player_photos, :allow_destroy => true

class PlayerPhoto < ActiveRecord::Base belongs_to :player_profile

It works but doesn't add new photo, it just replace the same every time.

     <%= nested_form_for @player_profile do |f| %>
      <%= f.fields_for :player_photos do |photo_form| %>
        <%= photo_form.file_field :photo %>

        <%= photo_form.link_to_remove "Hide" %>
      <% end %>
      <p><%= f.link_to_add "Add another photo", :player_photos %></p>

      <%=f.submit "Upload", :class => "button"%>
    <% end %>

If i use "text_field" instead of "file_field" it works correctly!

 <%= nested_form_for @player_profile do |f| %>
      <%= f.fields_for :player_photos do |photo_form| %>
        <%= photo_form.text_field :photo %>

        <%= photo_form.link_to_remove "Hide" %>
      <% end %>
      <p><%= f.link_to_add "Add another photo", :player_photos %></p>

      <%=f.submit "Upload", :class => "button"%>
    <% end %>
lest commented 11 years ago

Can you please provide a sample application that reproduces the error?

michaelfeihstel commented 10 years ago

Same problem here, though I'm pretty sure I know what the issue is: You upload a picture. Then you try that again and the first picture is overwritten. Right? You have to realize that you don't actually add a second picture on your second upload, but edit the child record you created on your first run. With a text field the behavior is clear since you'd actually see the already existing child record on your second (or nth) edit. With the view code you provided there's no way of knowing whether this is an existing or new child record - you display an upload form in any case - so you can't distinguish between creating and replacing. With that in mind, it works just fine if you upload multiple images in a single edit.

I just ran into this issue myself. In my case I'm dealing with the models product and product_images. Now I'm trying to only display the upload form(s) if the child record is a new/empty record and otherwise just show the already uploaded image. I'm having a hard time figuring out which object to call the new_record? method on though - using something along the lines of if @product_images.new_record? tells me that new_record? is undefined - the same is true for @product.product_images.new_record?. Can someone clarify how to access child object methods within the nested part of a form?