在出错时保留嵌套 fields_for 中的字段

Preserve field in nested fields_for on errors

我有一个表格

= form_for(@user_group, :html => {:multipart => true}do |f|
  = f.fields_for :image, @user_group.build_image do |ff|
    = ff.file_field :file
// other fields go here

它有效,但如果出现验证错误,它会重新呈现并且所选文件会消失(其他字段不会,包括其他嵌套属性)。 但是图像对象在那里:

def create
    @user_group = User::Group.new(user_group_params)
    if @user_group.save
      redirect_to @user_group
    else
      ap @user_group.image
      render :new
    end
  end

打印这个:

#<Image:0x007fbf11b902a8> {
               :id => nil,
      :imageble_id => nil,
    :imageble_type => "User::Group",
             :file => #<ImageUploader:0x007fbf11b46dd8 @model=#<Image id: nil, imageble_id: nil, imageble_type: "User::Group", file: nil, created_at: nil, updated_at: nil>, @mounted_as=:file, @cache_id="1441368278-5413-2848", @filename="snapshot3.png", @original_filename="snapshot3.png", @file=#<CarrierWave::SanitizedFile:0x007fbf11b44560 @file="/home/oleg/projects/10levels-rails/public/uploads/tmp/1441368278-5413-2848/snapshot3.png", @original_filename=nil, @content_type="image/png">, @versions={:thumb=>#<ImageUploader::Uploader70228906242320:0x007fbf11b44510 @model=#<Image id: nil, imageble_id: nil, imageble_type: "User::Group", file: nil, created_at: nil, updated_at: nil>, @mounted_as=:file, @parent_cache_id="1441368278-5413-2848", @cache_id="1441368278-5413-2848", @filename="snapshot3.png", @original_filename="snapshot3.png", @file=#<CarrierWave::SanitizedFile:0x007fbf11b39408 @file="/home/oleg/projects/10levels-rails/public/uploads/tmp/1441368278-5413-2848/thumb_snapshot3.png", @original_filename=nil, @content_type="image/png">, @versions={}>}>,
       :created_at => nil,
       :updated_at => nil
}

好像只是文件的问题

您可以使用 Carrierwave 的缓存功能。它保留选定的文件。

阅读this