简体   繁体   中英

Rails: ActiveRecord::RecordNotFound Couldn't find Photo without an ID

I have two models, Services and Photos. Under service model belongs_to :user and has_many :photos and has_many_attached :images.

Under photo model belongs_to :service

Under the Photos viewer I'm trying to display the images associated with each service.

I get a Couldn't find Image with an ID error when I try to delete an image.

The Viewer looks like this:

<% if @service.images.attached? %>
<br/><br/>

<div class="row">
  <% @service.images.each do |image| %>
    <div class="col-md-4">
      <div class="panel panel-default">
        <div class="panel-heading preview">
          <%= image_tag image %>
        </div>
        <div class="panel-body">
          <span class="pull-right">
            <%= link_to service_photo_path(@photos, image), remote: true, method: 'delete', data: {confirm: "Are you sure?"} do %>
              <i class="fa fa-trash-o" aria-hidden="true"></i>
            <% end %>
          </span>
        </div>
      </div>
    </div>
  <% end %>
</div>
<% end %>

The Photo Controller looks like this:

class PhotosController < ApplicationController

  def create
    @service = Service.find(params[:service_id])

    if params[:images]
      params[:images].each do |img|
        @service.photos.create(image: img)
    end

    @photos = @service.photos
    redirect_back(fallback_location: request.referer, notice: "Saved...")
  end
end

  def destroy
    @photo = Photo.find(params[:_id])
    service = @photo.service

    @photo.destroy
    @photos = Photo.where(service_id: service_id)

    respond_to :js
  end
end

routes:

service_photos POST /services/:service_id/photos(.:format)photos#create 
service_photo DELETE /services/:service_id/photos/:id(.:format) photos#destroy

Replace

@photo = Photo.find(params[:_id])

with:

@photo = Photo.find(params[:id])

I think you have typo! id not _id


Also, in your view replace:

service_photo_path(@photos, image)

with:

service_photo_path(@service, photo)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM