Reputation: 285
Hi everyone i am following the video tutorial for Jquery File Upload at http://railscasts.com/episodes/381-jquery-file-upload and am stuck. I after upload images my render partial does not refresh, it adds the new image and all other images under the image that was already attached. So if I add two images to a new item it shows the first image, then renders the partial again with the first image and the second image under the first so there are 3 photos in total.
Here is my create.js.erb
<% if @photo.new_record? %>
alert("Failed to upload photo: <%= j @photo.errors.full_messages.join(', ').html_safe %>");
<% else %>
$("#photos").append("<%=j render @photo %>");
<% end %>
Here is my render from my show page.
<div id="photos">
<%= render 'photos/photo' %>
</div>
Here is my /photos/_photos.html.erb partial
<h2>Images</h2>
<div class="photo">
<% @rental.photos.each do |photo| %>
<p>
<strong>Photo:</strong>
<%= image_tag photo.image_url.to_s %>
</script>
</p>
<% end %>
</div>
Here is my Photos Controller create
def create
@rental = Rental.find(params[:rental_id])
@photo = @rental.photos.create(params[:photo].permit(:image))
respond_to do |format|
format.js
end
end
Here is my photos.js.jcoffee
jQuery ->
$('#new_photo').fileupload(replaceFileInput: false,
paramName: 'photo[image]')
dataType: "script"
add: (e, data) ->
types = /(\.|\/)(gif|jpe?g|png)$/i
file = data.files[0]
if types.test(file.type) || types.test(file.name)
data.context = $(tmpl("template-upload", file))
$('#new_photo').append(data.context)
data.submit()
else
alert("#{file.name} is not a gif, jpeg, or png image file")
progress: (e, data) ->
if data.context
progress = parseInt(data.loaded / data.total * 100, 10)
data.context.find('.bar').css('width', progress + '%')
Any help would be great, I'm stuck. Thanks!
Thank you so much Rich Peck his answer fully solved my problem. I had to change
<% if @photo.new_record? %>
alert("Failed to upload photo: <%= j @photo.errors.full_messages.join(', ').html_safe %>");
<% else %>
$("#photos").append("<%=j render @photo %>");
<% end %>
To
<% if @photo.new_record? %>
alert("Failed to upload photo: <%= j @photo.errors.full_messages.join(', ').html_safe %>");
<% else %>
$("#photos").html("<%=j render @photo %>");
<% end %>
Upvotes: 7
Views: 7991
Reputation: 76784
def create
@rental = Rental.find(params[:rental_id])
@photo = @rental.photos.create(params[:photo].permit(:image))
respond_to do |format|
format.js
end
end
That's my first look at it
The fix was actually to use $('#photos').html()
to replace the container. The OP was originally using .append
to just append content to the container, which didn't work very well at all
Upvotes: 2