我的模型如下:
class User < ActiveRecord::Base
has_one :info, :class_name => "PostulantInfo"
mount_uploader :curriculum_vitae, DocumentUploader
#...
class PostulantInfo < ActiveRecord::Base
belongs_to :user
has_many :relatives
has_many :studies, :class_name => "HighSchoolStudy", :foreign_key => :postulant_info_id
mount_uploader :marriage_certificate, DocumentUploader
mount_uploader :photo1, FaceImageUploader
mount_uploader :photo2, SideFaceImageUploader
#...
class Relative < ActiveRecord::Base
mount_uploader :birth_certificate, DocumentUploader
#...
class HighSchoolStudy < ActiveRecord::Base
mount_uploader :degree_certificate, DocumentUploader
#...
实际上我只有默认的 store_dir:
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
所以这是创建一个目录结构,如:
- uploads
- user
- curriculum_vitae
- {user.id}
- {the_file}
-postulant_info
- marriage_certificate
- {postulant_info.id}
- {the_file}
- photo1
- {postulant_info.id}
- {the_file}
- photo2
- {postulant_info.id}
- {the_file}
- and so on...
但我想要类似的东西:
- uploads
- {user.uuid}
- {all_the_files_for_this_user}
问题是我不知道如何给出user.uuid
,例如,当我想marriage_certificate
保存PostulantInfo
. 我在wiki上找了一段时间,但找不到对这个问题有帮助的东西。
考虑一种可能的解决方案是为每个包含文件的模型添加一个 uuid 属性,然后将 user.uuid 复制到每个模型并将其保存到数据库,但这会浪费资源。
一个不那么混乱的解决方案可能是访问父模型,例如PostulantInfo
建模,并执行以下操作:
def store_dir
"uploads/#{model.user.uuid}"
end
但这意味着:
- 为每个后代级别制作一个上传者
- 添加
belongs_to :PostulantInfo
到Relative
andHighSchoolStudy
,这些模型没有理由知道它们的 Parent (除了明显知道 uuid) - 每次我想渲染文件的链接时,rails 都会进行 db 查询以了解 uuid,感谢 Devise in
current_user.uuid
实现这一目标的最佳方法应该是什么?提前致谢