Whenever I attempt to delete an image remotely within a view, I encounter the following error:
NoMethodError (undefined method `id' for #<Photo::ActiveRecord_Associations_CollectionProxy:0x007fa826898200>):
app/views/photos/destroy.js.erb:1:in `_app_views_photos_destroy_js_erb__997641922821004789_70180135669200'
app/controllers/photos_controller.rb:31:in `destroy'
This is the destroy
method that I am using:
def destroy
@photo_destroy = Photo.find_by_id(params[:id])
@item = Item.find(@photo_destroy.item_id)
if @photo_destroy.present?
@photo_destroy.destroy
end
flash[:success] = "Photo deleted"
@photo = @item.photos
respond_to do |format|
format.html { redirect_to edit_photos_url(@item)}
format.js
</end
Here is the relevant section of my JavaScript for destroying:
$("#photo-<%= @photo.id %>").html("<%= escape_javascript(render('photos/showpics')) %>");
And this is the partial view being utilized:
<div class="row">
<% @photo.each do |photo| %>
<li id="photo-<%= photo.id %>">
<div class="col-sm-6 col-md-4">
<div class="thumbnail" >
<%= image_tag photo.image_url(:thumb) if photo.image? %>
<div class="caption">
<%= photo.title %>
<p><a href="#" class="btn btn-primary" role="button"><%= link_to 'Remove', delete_photo_path(photo), method: :delete, remote: true %></a></p>
</div>
</div>
</div>
</li>
<% end %>
</div>
I suspect there may be a disconnect between the @photo
variable in the view and the destroy action in the destroy
method. Is it possible to pass @photo
from the method to the JavaScript, or is there a better approach to resolve this issue?