How to remove images corresponding to a column when removing the column

问题内容:

I am using rails 4.2.1, ruby 2.3.0p0 and carrierwave(0.11.0) in my project. Currrently I have a model Product with image column. Now, I want to save multiple images for same product. So I have created a new model ProductImage and used following code

Product.all.each do |prdct|
  if prdct.image.present?
    @photo = prdct.product_images.create!(image: prdct.image)
    prdct.remove_image!
  end
end
remove_column :products, :image

But the image saved in product/image folder is not getting removed. How can I remove the image after moving it under ProductImage model

问题评论:

    
Perhaps product.image.destroy?

答案:

答案1:

After prdct.remove_image! you have to save (prdct.save) the object so that it can be removed.

If you want to the delete the folder as well, you’ll have to do something like this:

def remove_image_directory
 FileUtils.remove_dir("#{Rails.root}/path/to/folder/", force: true)
end

And call this method after deleting the image.

From the docs:
https://github.com/carrierwaveuploader/carrierwave#removing-uploaded-files

答案评论:

    
It worked. Image is deleted but the folder is not getting deleted. Can we delete the folder also?
– CR7
10 hours ago
    
@CR7 Updated my answer.

原文地址:

https://stackoverflow.com/questions/47746509/how-to-remove-images-corresponding-to-a-column-when-removing-the-column

添加评论