删除上传的图片- Rails 4 Carrierwave

3
尝试使用CarrierWave删除上传的图像
<%= f.fields_for :images do |ff| %>
   <div class="form-group">
      <label>
        <%= ff.check_box :remove_image %>
          <%= image_tag ff.object.image %>
        </label>
      </div>
<% end %>

在控制器中获取这些参数
"images_attributes"=>{"0"=>{"remove_image"=>"0", "id"=>"13"}, "1"=>{"remove_image"=>"1", "id"=>"14"}, "2"=>{"remove_image"=>"0", "id"=>"15"}, "3"=>{"remove_image"=>"0", "id"=>"16"}, "4"=>{"remove_image"=>"0", "id"=>"17"}, "5"=>{"remove_image"=>"0", "id"=>"18"}}}

但是当使用这些参数更新对象时,没有任何变化,我错过了什么?

更新

  def update
    @country = Country.find(params[:id])

    if @country.update(country_params)
      flash[:notice] = 'Country is successfully updated.'
      redirect_to edit_admin_country_path
    else
      flash[:error] = @country.errors.full_messages[0]
      render 'edit'
    end
  end

  def country_params
    permitted = [{images_attributes: ["image", "@original_filename", "@content_type", "@headers", "_destroy", "id", "remove_image"]}]
    params.require(:country).permit(*permitted)
  end

 class Country < ActiveRecord::Base
    has_many :images
    ....
 end

class Image < ActiveRecord::Base

  mount_uploader :image, ImageUploader
  belongs_to :country
end

有没有控制器可以查看您尝试删除这些图像的方式? - Sebastián Palma
请分享你的模型。 - Asad Ali
更新了我的帖子。 - Aydar Omurbekov
1个回答

10

你的表单看起来不错,但你缺少控制器操作。

我的表单如下:

class ImageController < ApplicationController
  ...
  def update
    @image = Image.find(params[:id])
    ...
    if params[:images][:remove_image].present?
      @image.remove_image!
    end
    @image.save
  end
end
如果您想手动删除文件,可以调用remove_avatar!,然后保存该对象。

我想一次性删除所有图片,我不介意循环和删除,但希望能找到更优雅的方法。 - Aydar Omurbekov
无论如何,非常感谢您的帮助! - Aydar Omurbekov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接