Oleg Antonyan
Oleg Antonyan

Reputation: 3113

Preserve field in nested fields_for on errors

I have a form

= 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

It works, but if there is a validation error it gets rerendered and selected file disappear (other fields does not, including other nested attributes). But image object is there:

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

Prints this:

#<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
}

Seems like it is a problem with files only

Upvotes: 1

Views: 142

Answers (1)

Faizan
Faizan

Reputation: 383

You can use caching feature of Carrierwave. It preserves file selected.

Read this

Upvotes: 1

Related Questions