4

I'm not sure what I'm doing wrong here. File uploads are working but if I submit the form without selecting a file to upload it deletes the previously attached image(s).

Here's what the ActiveAdmin form looks like:

form do |f|
  f.inputs do
    f.input :model_number
    f.input :description
    f.input :slug
    f.input :categories
    f.has_many :product_images do |image|
      image.input :product_id, as: :hidden, id: :product_id, input_html: { value: "%i" }
      image.input :image
    end
  end
  f.actions
end

And the relevant parts of the respective models:

class ProductImage < ActiveRecord::Base
  belongs_to :product

  mount_uploader :image, ProductImageUploader

  validates :image, :product_id, presence: true
end

class Product < ActiveRecord::Base
  has_many :product_images, dependent: :destroy

  accepts_nested_attributes_for :product_images

  validates_associated :product_images
end

Any insights would be much appreciated. Thanks!

Besi
  • 22,579
  • 24
  • 131
  • 223
Ryan Linton
  • 1,285
  • 1
  • 14
  • 20
  • Check out this SO question for a possible workaround: http://stackoverflow.com/questions/5009550/carrierwave-upload-with-nested-forms. Although, using CarrierWave's form redisplay cache may be a better alternative. See the [docs](https://github.com/carrierwaveuploader/carrierwave#making-uploads-work-across-form-redisplays) for more information. Does it only happen via accepts_nested_attributes_for subforms? – Charles Maresh Nov 12 '13 at 14:06

1 Answers1

4

It looks like I was a bit overzealous with my validations. Removing product id from the ProductImages validations and simplifying image.input :product_id, as: :hidden, id: :product_id, input_html: { value: "%i" } in the form to image.input :product_id, as: :hidden in the form makes image attach correctly to existing products or new products.

Ryan Linton
  • 1,285
  • 1
  • 14
  • 20