编辑时上传 Rails 文件(回形针) [英] Rails file upload (paperclip) on edit

查看:28
本文介绍了编辑时上传 Rails 文件(回形针)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为自己制作了一个简单的 rails 博客类型应用程序,我使用 Paperclip 上传图像文件.我一切正常.我什至将它连接到 S3 存储桶等.漂亮吧?

I made myself a simple rails blogging-type app where I use Paperclip to upload image files.I have everything working fine and dandy. I even have it hooked up to an S3 bucket, etc. Spiffy right?

但是我不知道在编辑/更新帖子时该怎么做.就目前而言,我所拥有的只是表单模板上的这个字段:

But I can't figure what to do when EDITING/UPDATING a post. As is stands now, all I have is this field on my form template:

= f.file_field :image

因此,即使有先前附加的图像,在post/5/edit"上说,该字段也会显示未选择文件".

So, say on "post/5/edit" even if there's a previously attached image, the field displays "No file chosen".

更糟糕的是,如果我改变主意并且不想附加图像,则没有明显的方法可以清除当前图像.

Even worse, there's no apparent way to clear out current image if I change my mind and don't want to attach an image.

我如何使这对用户更友好,并确保当前图像——文本/url 很好——显示为文本字段中的值和/或用户可以将当前图像更改为无.

How do I make this a little more user-friendly and make sure the current image -- text/url is fine -- shows up as the value in the text field and/or the user can change the current image to none.

推荐答案

对于 Rails3,这就是我所做的.抱歉,我还没用过 Rails4.

For Rails3 here's what I do. Sorry, I haven't used Rails4 yet.

要向用户显示他们是否已经上传了文件,请在您的视图中执行此操作:

To display to the user if they have already uploaded a file, do this in your view:

<% if @blog.image.exists? %>
  <%= image_tag @blog.image.url(:thumb) %><br/>
<% end %>
<%= f.file_field :image %>

然后,为了允许用户删除当前上传的内容,将其添加到您的视图中(在 if 块内):

Then, to allow for the user to remove the current upload add this to your view (inside that if block):

<%= f.check_box :delete_image %>Delete Image<br/>

然后您在模型中处理该复选框:

And you handle that checkbox in your model:

  before_validation { image.clear if @delete_image }

  def delete_image
    @delete_image ||= false
  end

  def delete_image=(value)
    @delete_image  = !value.to_i.zero?
  end

这样,如果用户设置了复选框,它将在下次保存时清除图像.

That way if the user sets the checkbox it will clear the image on the next save.

这篇关于编辑时上传 Rails 文件(回形针)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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