Rails + Dragonfly gem: Saving image in a directory structure based on ActiveRecord object attributes
-
01-10-2019 - |
Question
I'm using dragonfly gem to manage images and attachments in my rails app and I need to store images in a specific directory structure based on my
user model.
let' say I have user model which has a name and each user has many
albums, which have a name also, then I want the images to be stored
in "#{RAILS_ROOT}/public/system/#{user.name}/#{user.album.name}/#{suffix}"
I've managed to changed the root_path in dragon fly and I even overrided relative_storage_path like this:
class MyDataStore < Dragonfly::DataStorage::FileDataStore
private
def relative_storage_path(suffix)
"#{suffix}"
end
end
but still, I don't know how I can pass the ActiveRecord object
attributes like user.name
and user.album.name
to relative_storage_path
to create my ideal path.
do you have any idea how I can do such a thing?
Solution
Mark Evans the gem author did me a favor and answered this question on google group. Here is his answer that worked pretty well for my case:
Hi there
You can't do this out of the box, because the data store is purposefully designed to be very simple - you pass in data, it gives you back a uid, etc.
If you want to do it you'll have to monkey-patch Attachment#save! like so:
class Dragonfly::ActiveRecordExtensions::Attachment
def save!
destroy! if uid_changed?
self.uid = app.datastore.store(temp_object, parent_model) if has_data_to_store?
end
end
The only thing I've changed above is that datastore.store takes two args now.
You'll then have to modify/monkey-patch Dragonfly::DataStorage::FileDataStore#store to take into account the second arg.
Out of interest, why do you want the images to be stored in that format?
Cheers Mark