Reputation: 175
I recently implemented Carrierwave in a project and got it working for one model. I have tried extending the same code to another model and for some reason the images won't save.
Both model tables contain a column for 'images' in the schema that is of type 'text'.
Both models have the following lines at the top:
mount_uploaders :images, ImageUploader
serialize :images, JSON
I have a private method in both controllers permitting the images:
def images_param
params.require(:image_files).permit!
end
And I add the images to the object in the #update action of both controllers as so:
object.images = images_param.values
object.save
byebug
What's confusing me is that this works well for one of the models, but fails for the other. Moreover, when I use byebug to inspect the object, the model that works shows the images added to the object, while the other model shows images as 'nil'.
Here is the (working) byebug output for object1:
#<PageAppearance id: 10, images: ["image-1.png"]>
Here is the (working) byebug output for object1.images:
[#<ImageUploader:0x00007f8bb5eb43d8 @model=#<PageAppearance id: 10, images: ["image-1.png"]>, @mounted_as=:images, @cache_id=nil, @filename="image-1.png", @original_filename="image-1.png", @file=#<CarrierWave::SanitizedFile:0x00007f8bb736d400 @file="/Users/agaus/environment/namc-portal_/public/uploads/page_appearance/images/10/image-1.png", @original_filename=nil, @content_type="image/png">, @cache_storage=#<CarrierWave::Storage::File:0x00007f8bb5eacd90 @uploader=#<ImageUploader:0x00007f8bb5eb43d8 ...>>, @versions={}, @storage=#<CarrierWave::Storage::File:0x00007f8bb1f8a888 @uploader=#<ImageUploader:0x00007f8bb5eb43d8 ...>>>]
>
Here is the (failed) byebug output for object2:
#<Question id: 276, images: nil>
Here is the (failed) byebug output for object2.images:
[#<ImageUploader:0x00007f8bb80f7620 @model=#<Question id: 276, images: nil>, @mounted_as=:images, @storage=#<CarrierWave::Storage::File:0x00007f8bb80eb7d0 @uploader=#<ImageUploader:0x00007f8bb80f7620 ...>>>]
>
If anyone has any idea why this might be happening I would greatly appreciate it!
Upvotes: 2
Views: 294
Reputation: 175
So, turns out I didn't have enctype set to multipart in my form tag (which is required for uploading files via forms). Changing <%= form_for @question do |f| %>
to <%= form_for @question, html: {multipart: true} do |f| %>
fixed the problem.
Upvotes: 2