Reputation: 8372
I am using Carrierwave to upload an image from a remote url :
def save
uid = SecureRandom.uuid
storedir = "uploads/#{uid}"
image = Image.new
image.image.store_dir = storedir
image.remote_image_url = "a remote url here"
if image.save!
respond_to do |format|
format.js
format.json { render json: {:saved => "#{image.image_url}", :id => "#{image.id}"} }
end
end
end
the returned result is correct :
Object { saved="https://mybucket.s3-eu-west-1.amazonaws.com/uploads/58406672-c227-4cec-a846-04c443e70f33/thumb_yr169-ae2f3bc4-74f4-47ee-950c-2e06756525b9-v2.png", id="47"}
As you can see the image url is this :
https://mybucket.s3-eu-west-1.amazonaws.com/uploads/58406672-c227-4cec-a846-04c443e70f33/thumb_yr169-ae2f3bc4-74f4-47ee-950c-2e06756525b9-v2.png
and when I go to check the file, it's there in the right folder, but when I go to the Rails Console and look for that record, the result of image_url is wrong :
> Rails console
> Image.find(47).image_url
> https://mybucket.s3-eu-west-1.amazonaws.com/uploads/thumb_yr169-ae2f3bc4-74f4-47ee-950c-2e06756525b9-v2.png
The uid after /uploads/ is gone!!
any help please!!
UPDATE
Looks like carrierwave is go check store_dir in the uploader to show the image url, in my case I override it before saving the image, and I would like to use that custom store_dir
Upvotes: 1
Views: 1044
Reputation: 5623
Yeah, that is because CarrierWave, like most similar libraries try to build your url dynamically.
Add this to your ImageUploader
#ImageUploader
def uid
'58406672-c227-4cec-a846-04c443e70f33'
end
def store_dir
"uploads/#{uid}"
end
#XController
def save
image = Image.new
image.remote_image_url = "a remote url here"
if image.save!
respond_to do |format|
format.js
format.json { render json: {:saved => "#{image.image_url}", :id => "#{image.id}"} }
end
end
end
UPDATE
Not totally sure of why you'd want to overide the store, but in order to do that, I think you may be better served by storing the additional details on the images
table as such:
Image
model, which may be the store_uidIn your ImageUploader, change your store_dir
to use your builder or the field name, e.g if the column on Image is store_uid
, with value: whatever-uid-has-been-stored-here
, you could do:
def store_dir
# /uploads/whatever-uid-has-been-stored-here
"uploads/#{model.store_uid}"
end
A cleaner approach and one that's often advised is to create another uploader for each kind of images, for consistency within your application
Upvotes: 1