How to use nested_form gem with a different partial for new vs. existing nested model objects?
I am using the nested_form gem but ran in to 开发者_运维知识库one use case that is giving me some trouble. I have one particular nested form where the partial for existing nested objects is different from the one needed when adding a new object. (The particular use case is images - existing uploaded images display an image tag, new image objects need to render a file_field for upload.)
One thing I tried is to check within the partial for f.object.nil? to determine what to render but both new and existing objects still yielded the existing object partial code. I'm assuming this has something to do with the way the nested_form BuilderMixin is calling fields_for?
Is there an easy way to do this that I am missing? Or do I need to look at modifying the nested_form link_to_add code to accommodate this?
For reference, here was my attempt at using one partial:
<tr>
<% if !f.object.nil? %>
<td>
<a href="/customer_images/<%= f.object.id %>" target="_new">
<%= image_tag f.object.picture.url -%>
</a>
</td>
<td>
Description: <%= f.object.image_description %><br/>
Date Uploaded: <%= (f.object.nil? || f.object.created_at.nil?) ? "Not yet uploaded." : f.object.created_at.strftime("%A %h %d, %Y %I:%M %p") %>
<br>
<%= f.link_to_remove "Remove this image" %>
</td>
<% else %>
<td> </td>
<td>
<%= label :image, :file, "Select File:" %><%= f.file_field :picture %><br />
Description: <%= f.text_field :image_description %><br />
</td>
<% end %>
</tr>
No object could be nil
there. You should check whether or not the object exists in database calling the new_record?
method.
See doc.
精彩评论