保留嵌套fields_for中的字段以查找错误

时间:2015-09-04 12:13:24

标签: ruby-on-rails nested-attributes

我有一张表格

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

似乎只是文件的问题

1 个答案:

答案 0 :(得分:1)

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

阅读this