Is it possible to have a dynamic storage path with carrierwave?

陌路散爱 提交于 2019-12-05 02:50:38

问题


I am starting with carrierwave for file uploads and have been quite happy with it so far. My files are stored on amazon s3 which was fairly easy and it works reliably.

Now I have a model named pictures and an uploader name MainUploader. I need a special dynamic path to save those files to when uploaded.

I am also using devise and I have the current_user I can access from my views and controller but not from the carrierwave uploader. I need the path of the file to be something like

uploads/#{current_user.location}/#{current_user.first_name}/images

but I cannot access the current_user from the uploader and haven't seen any alternatives. Is this type of dynamic path possible with carrierwave (without re-writing large amounts of this gem)?

Any pointers are greatly appreciated. Thank you for your help.


回答1:


Just in case anyone else wondered here from a google search or something.

What I ended up doing was creating a belongs_to relationship on my model (pictures) to the User model. Then from carrierwave uploader I can do model.user.first_name which is the equivalent of picture.user.first_name. So I can put that model.user in my path and access any user attribute in that way. Hope this helps someone else.

Something like:

def store_dir
    "#{model.user.first_name}/uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.title}"
end

ps Note I also used model.title that is because I want the picture.title to be in the path as well. Not best practice though. If you do this make sure you parse model.title in production so it gives you a valid folder name/url.



来源:https://stackoverflow.com/questions/8470803/is-it-possible-to-have-a-dynamic-storage-path-with-carrierwave

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!