是否可以使用载波进行动态存储路径? [英] Is it possible to have a dynamic storage path with carrierwave?

查看:98
本文介绍了是否可以使用载波进行动态存储路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始使用载波Wave 进行文件上传,到目前为止已经很开心了。我的文件存储在亚马逊s3这是相当容易,它可靠地工作。

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.

现在我有一个模型名为图片和上传者名称 MainUploader 。我需要一个特殊的动态路径来将这些文件保存到上传时。

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.

我也在使用devise,我有 current_user 我可以从我的视图和控制器访问,但不能从载波上传器访问。我需要该文件的路径,就像

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

但我无法从上传者访问current_user,没有看到任何选择。这种类型的动态路径可能与载波(不重写大量的这个宝石)吗?

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.

推荐答案

只要有人在谷歌搜索或某事上想到这里。

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

我最后做的是在我的模型(图片)上创建一个belongs_to关系到用户模型。然后从载波上传器我可以执行 model.user.first_name ,这相当于 picture.user.first_name 。所以我可以将该model.user放在我的路径中,并以这种方式访问​​任何用户属性。希望这可以帮助别人。

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.

如下所示:

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

ps
注意我也使用了 model.title 因为我想要picture.title也在路径中。不是最好的做法。如果这样做,请确保在生产中解析model.title,以便它为您提供有效的文件夹名称/网址。

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.

这篇关于是否可以使用载波进行动态存储路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆