Rails Paperclip 如何删除附件? [英] Rails Paperclip how to delete attachment?

查看:55
本文介绍了Rails Paperclip 如何删除附件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Rails 3 上使用 Paperclip(带 Amazon s3).我想删除现有附件使用更新操作替换它.

I am using Paperclip (w/ Amazon s3) on Rails 3. I want to delete an existing attachment without replacing it using an update action.

我只在此处找到了一个示例,但找不到让它工作,它只是不会删除,日志中也没有说明原因.我想在表单上做这样的事情:

I've only found one example of this here and could not get that to work, it just wouldn't delete and there was nothing in the logs to say why. I wanted to do something like this on the form:

<%- unless @page.new_record? || !@page.image? -%>
    <%= f.check_box :image_delete, :label => 'Delete Image' %>
<%- end -%>

(page是模型的名字,image是保存附件的属性名)

(page is the name of the model, image is the attribute name which holds the attachment)

但我如何检测该复选框,更重要的是,如何删除图像?感谢您的帮助!

But how do I detect that checkbox and more importantly, how do I delete the image? I appreciate any help!

推荐答案

首先,当你在 form_for 中创建一个 check_box(它看起来像你),那么表单应该默认发送 :image_delete 为1"如果选中,则0"如果未选中.方法声明如下所示:

First off, when you create a check_box in a form_for (which it looks like you are), then the form should by default send :image_delete as "1" if checked and "0" if unchecked. The method declaration looks like this:

def check_box(method, options = {}, checked_value = "1", unchecked_value = "0")

这表明您可以根据需要分配其他值,但这当然是可选的.

Which shows that you can assign other values if you want to, but that is of course optional.

其次,手动删除附件而不删除它所附加的模型实例的调用是:

Secondly, the call to manually delete an attachment without deleting the model instance to which it is attached to is:

@page.image.destroy #Will remove the attachment and save the model
@page.image.clear #Will queue the attachment to be deleted

为了完成您通过复选框删除图像的方式,可以在您的页面模型中添加如下内容:

And to accomplish your way of deleting the images through a checkbox, perhaps add something like this to your Page model:

class Page < ActiveRecord::Base
  has_attached_file :image

  before_save :destroy_image?

  def image_delete
    @image_delete ||= "0"
  end

  def image_delete=(value)
    @image_delete = value
  end

private
  def destroy_image?
    self.image.clear if @image_delete == "1"
  end
end

这样,当您创建表单并添加 :image_delete 复选框时,它将从 User 实例加载默认值0".如果该字段被选中,那么控制器会将 image_delete 更新为1",当用户保存时,它会检查是否要删除图像.

This way, when you create your form and add the :image_delete checkbox, it will load the default value "0" from the User instance. And if that field is checked then the controller will update the image_delete to "1" and when the User is saved, it will check if the image is to be deleted.

这篇关于Rails Paperclip 如何删除附件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆