Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Carrierwave upload with nested forms?

Not sure what's going on here, but I think my nested form partials are causing a problem for CarrierWave.

When I update a field with an uploaded file, nothing happens: no error, but nothing stored either.

I have a "Household" model with a "has_many" relationship with an "Individuals" model. The "Individuals" model has a "picture" uploader:

class Individual < ActiveRecord::Base
    belongs_to :household
    mount_uploader :picture, PictureUploader
end

In my views I have:

= form_for @household, :html => {:multipart => true} do |f|

and then call a partial for the individuals:

= f.fields_for :individuals do |builder|
  = render 'individual_fields', :f => builder

= f.submit

The partial just has the following:

= f.label :firstname, 'First'
= f.text_field :firstname, :size => 10
= f.label :lastname, 'Last'
= f.text_field :lastname, :size => 15
= f.file_field :picture

The uploaded picture appears in the params:

Started POST "/households/849" for 127.0.0.1 at 2011-02-15 15:45:16 -0500
  Processing by HouseholdsController#update as HTML
  Parameters: {"...6/1/2008; Active 6/6", "individuals_attributes"=>{"0"=>{"firstname"=>"Hannah", ... 
  "picture"=>#<ActionDispatch::Http::UploadedFile:0xb9fbd24 @original_filename="3.jpg",
  @content_type="image/jpeg", @headers="Content-Disposition: form-data; 
  name=\"household[individuals_attributes][1][picture]\"; filename=\"3.jpg\"\r\nContent-Type: 
  image/jpeg\r\n", @tempfile=#<File:/tmp/RackMultipart20110215-6498-ba4bp>>, "_destroy"=>"false", 
  "id"=>"4077"}}}, "commit"=>"Update Household", "id"=>"849"}

And is stored in the tmp directory under the upload path. It's just never saved to the database, nor moved into place in the filesystem.

Any ideas?

like image 440
thermans Avatar asked Feb 15 '11 21:02

thermans


1 Answers

Some possible solutions:

  • It looks like you have, but just to make sure - have you got accepts_nested_attributes on the household model?
  • Also, have you tried it without the partial to localise the problem?
  • Have you got Rmagick or minimagick on the PictureUploader model?

And also you'll want to note of the known issue with Carrierwave and nested forms as detailed on the Carrierwave Wiki.

The workaround is to add the method below:

class Image < ActiveRecord::Base
  mount_uploader :image, ImageUploader

  def image=(val)
    if !val.is_a?(String) && valid?
      image_will_change!
      super
    end
  end

end
class Person < ActiveRecord::Base
  has_many :images
  accepts_nested_attributes_for :images
end
like image 152
Galaxy Avatar answered Sep 30 '22 14:09

Galaxy