由于验证错误而无法保存模型时不会丢失回形针附件 [英] Not losing paperclip attachment when model cannot be saved due to validation error
问题描述
该场景是一个普通模型,其中包含一个回形针附件以及一些其他具有各种验证的列.当用于创建对象的表单由于与附件无关的验证错误而无法保存时,会保留字符串等列并为用户预先填充,但选择用于上传的文件完全丢失,必须由用户重新选择.
The scenario is a normal model that contains a paperclip attachment along with some other columns that have various validations. When a form to to create an object cannot be saved due to a validation error unrelated to the attachment, columns like strings are preserved and remain prefilled for the user, but a file selected for uploading is completely lost and must be reselected by the user.
是否有标准方法可以在模型验证错误的情况下保留附件?这似乎是一个非常常见的用例.
在没有所有者的情况下保存文件然后在成功保存后重新连接到对象的解决方案似乎不雅,所以我希望避免这种情况.
It seems inelegant to hack up a solution where the file is saved without an owner and then reconnected to the object after it's successfully saved so I'm hoping to avoid this.
推荐答案
改用 CarrierWave.我知道这是在评论中,但我只是花了一整天时间进行转换,所以我的回答可能仍然有帮助.
Switch to using CarrierWave. I know this was in a comment, but I just spent all day making the transition so my answer may be helpful still.
首先,您可以关注有关设置载波的精彩 railscast:http://railscasts.com/episodes/253-carrierwave-file-uploads
First you can follow a great railscast about setting up carrier wave: http://railscasts.com/episodes/253-carrierwave-file-uploads
要让它保留帖子之间的图像,您需要添加一个后缀为'cache'的隐藏字段:
To get it to preserve the image between posts, you need to add a hidden field with the suffix 'cache':
<%= form_for @user, :html => {:multipart => true} do |f| %>
<p>
<label>My Avatar</label>
<%= f.file_field :avatar %>
<%= f.hidden_field :avatar_cache %>
</p>
<% end %>
对于 Heroku
如果您像我一样部署到 Heroku,则需要进行一些更改才能使其正常工作,因为缓存是通过将上传临时保存在名为 public/uploads 的目录中来工作的.由于文件系统在 Heroku 中是只读的,您需要让它使用 tmp 文件夹,并让机架从那里提供静态文件.
For Heroku
And if you're deploying to Heroku like I am, you need to make some changes to get it to work, since the caching works by temporarily saving uploads in a directory called public/uploads. Since the filesystem is readonly in Heroku, you need to have it use the tmp folder instead, and have rack serve static files from there.
在您的 config/initializers/carrierwave.rb(如果没有,请随意创建),添加:
In your config/initializers/carrierwave.rb (feel free to create if not there), add:
CarrierWave.configure do |config|
config.root = Rails.root.join('tmp')
config.cache_dir = 'carrierwave'
end
配置机架以提供 tmp/carrierwave 文件夹中的静态文件
在您的 config.ru 文件中,添加:
Configure rack to serve static files in from the tmp/carrierwave folder
In your config.ru file, add:
use Rack::Static, :urls => ['/carrierwave'], :root => 'tmp'
有关功能齐全的准系统 rails/carrierwave/s3/heroku 应用程序的示例,请查看:
For an example of a fully functional barebones rails/carrierwave/s3/heroku app, check out:
https://github.com/trevorturk/carrierwave-heroku(没有从属关系,只是很有用).
https://github.com/trevorturk/carrierwave-heroku (no affiliation, just was useful).
希望这有帮助!
这篇关于由于验证错误而无法保存模型时不会丢失回形针附件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!