繁体   English   中英

传递嵌套资源的ID以删除Rails中的文件

[英]passing id of a nested resource for deleting a file in rails

我有很多照片的清单。 所以我正在使用嵌套资源。 但是现在面临的问题是我无法删除单张照片。 我可以看到它,因为照片ID为零。

这是我的photos_controller

class PhotosController < ApplicationController


  before_action :set_listing

  def index
    @photos = @listing.photos.all

  end

  def create
    @photo = @listing.photos.new(photo_params)
    if @photo.save
      respond_to do |format|
        format.js
      end
    end
  end

  def destroy
    @photo = @listing.photos.find(params[:id])
    @photo.destroy
    redirect_to photos_url, notice: 'Photo was successfully destroyed.'
  end

  private



  def set_listing
    @listing = Listing.find(params[:listing_id])
  end

  def photo_params
    params.require(:photo).permit(:image, :remove_image)
  end
end

routes.rb

 resources :listings do
    resources :photos, only: [:index, :create, :destroy]
   end

在我的索引页面中,我有一个div通过局部index.html.erb显示图像

create.html.erb

$("#photos div").append("<%= j render(@photo) %>")

这是我的局部照片

_photo.html.erb

          <div class="col-md-4">
            <div class="panel panel-default">
              <div class="panel-heading-preview">
                <%= image_tag photo.image_url(:thumb) %>
              </div>
              <div class="panel-body">
          <span class="pull-right">
            <%= link_to "#", remote: true, method: :delete, data: {confirm: "Are you sure?"} do %>
      <i class="fa fa-times fa-lg"></i>
                <% end %>
          </span>
              </div>
            </div>
          </div>

在_photo.html.erb中,我也尝试过

<%= link_to listing_photo_path(photo.id), remote: true, method: :delete, data: {confirm: "Are you sure?"} do %>

但是在加载索引页面时出现此错误

没有路线匹配{:action =>“ destroy”,:controller =>“ photos”,:id => nil,:listing_id => 1}缺少必需的键:[:id]

所有照片都有ID,如果我将照片的ID硬编码,则可以轻松删除它。 有人可以告诉我这里做错了什么吗?

您还应该提供Listing ID,因为您具有嵌套资源:

<%= link_to listing_photo_path(@listing, photo) # etc. %>

或者简单地:

<%= link_to [@listing, photo] # etc %>

当您的路由中有嵌套资源时,就像您一样,将有两个级别的identifying ids ,如下所示:

resources :listings do
  resources :photos, only: [:index, :create, :destroy]
end

嵌套照片的典型网址(如果您检查rake routes )将如下所示:

/listings/:listing_id/photos/:id

这意味着你需要提供最多两个标识符( listing_idid首位,而其照片ID)

因此,在您指向destroy方法的链接中,您需要做的只是包括以下内容:

<%= link_to listing_photo_path(listing_id: @listing.id, id: photo.id), remote: true, method: :delete, data: {confirm: "Are you sure?"} do %>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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