Reputation: 4893
I am posting an image (or multiple images) to my controller via Javascript. I am using Carrierwave + Rails 5 for image uploads.
The image comes across in the params like this:
<ActionController::Parameters {"file"=><ActionController::Parameters {"0"=>#<ActionDispatch::Http::UploadedFile:0x00007fcc92da6c70 @tempfile=#<Tempfile:/var/folders/3m/9jgntpps1j5gzkm444tq6t400000gn/T/RackMultipart20180208-2884-15wx288.jpeg>, @original_filename="1.jpeg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"file[0]\"; filename=\"1.jpeg\"\r\nContent-Type: image/jpeg\r\n">} permitted: false>, "controller"=>"listings", "action"=>"create"} permitted: false>
I am trying to allow that into my controller somehow. This seems to fail:
@listing.pictures = params[:file]
ActiveRecord::AssociationTypeMismatch: Picture(#70258317227420) expected, got "0" which is an instance of String(#70258262105620)
This also seems to fail:
@listing.pictures = params[:file]['0']
NoMethodError: undefined method `each' for #<ActionDispatch::Http::UploadedFile:0x00007fcc92da6c70>
I'm not sure how to add the pictures to my model from this POST request. Any ideas?
The relation between Listing and Picture looks like this:
class Listing < ApplicationRecord
has_many :pictures, as: :imageable, dependent: :destroy
end
class Picture < ApplicationRecord
belongs_to :imageable, polymorphic: true
mount_uploader :image, ImageUploader
end
Thanks in advance!
Upvotes: 0
Views: 255
Reputation: 115521
try the following:
@listing.pictures = params[:file].values.map {|file| Picture.new(image: file)}
Upvotes: 2