关联模型中存储的载波文件路径
Carrierwave file path stored in associated model
我的结构
class Project
include Mongoid::Document
has_many :documents MyUploader
def directory
...
end
class Document
include Mongoid::Document
belongs_to :project
mount_uploader :physical_doc
def directory
folder = File.join(self.project.directory, self.class::SUBFOLDER)
Dir.mkdir(folder) unless File.exists?(folder)
folder
end
class MyUploader < CarrierWave::Uploader::Base
def store_dir
nil
end
def cache_dir
self.model.directory
end
我文档的存储目录只有项目知道(位置可能会改变,Project
class 负责移动文档以防万一)
问题
删除文档时,Rails 将按照它们在代码中出现的顺序删除 "fields"。也就是说
- 它会先删除
:project
关联
- 然后它将删除
mount_uploader :physical_doc
- ... 但是载波 mount_uploader 需要知道文件的存储位置才能删除文件!哦哦....
换句话说,这两段代码是不等价的
class Document
mount_uploader :physical_doc
belongs_to :project
# This allows the document to be deleted, not created
class Document
belongs_to :project
mount_uploader :physical_doc
# This allows the document to be created, not deleted
解决方案?
添加我的评论作为答案(我可以使用一些积分)。
也许在使用您发布的第二个代码段时使用 before_destroy
回调来实际删除文件?
before_destroy { attachment.file.destroy if attachment.file.exists? }
我的结构
class Project
include Mongoid::Document
has_many :documents MyUploader
def directory
...
end
class Document
include Mongoid::Document
belongs_to :project
mount_uploader :physical_doc
def directory
folder = File.join(self.project.directory, self.class::SUBFOLDER)
Dir.mkdir(folder) unless File.exists?(folder)
folder
end
class MyUploader < CarrierWave::Uploader::Base
def store_dir
nil
end
def cache_dir
self.model.directory
end
我文档的存储目录只有项目知道(位置可能会改变,Project
class 负责移动文档以防万一)
问题
删除文档时,Rails 将按照它们在代码中出现的顺序删除 "fields"。也就是说
- 它会先删除
:project
关联 - 然后它将删除
mount_uploader :physical_doc
- ... 但是载波 mount_uploader 需要知道文件的存储位置才能删除文件!哦哦....
换句话说,这两段代码是不等价的
class Document
mount_uploader :physical_doc
belongs_to :project
# This allows the document to be deleted, not created
class Document
belongs_to :project
mount_uploader :physical_doc
# This allows the document to be created, not deleted
解决方案?
添加我的评论作为答案(我可以使用一些积分)。
也许在使用您发布的第二个代码段时使用 before_destroy
回调来实际删除文件?
before_destroy { attachment.file.destroy if attachment.file.exists? }