Rails + Dragonfly gem:基于ActiveRecord对象属性将图像保存在目录结构中

All*_*rgi 1 ruby ruby-on-rails image paperclip dragonfly-gem

我正在使用dragonfly gem来管理我的rails应用程序中的图像和附件,我需要根据我的用户模型将图像存储在特定的目录结构中.让我说我的用户模型有一个名字,每个用户有很多专辑,也有一个名字,然后我希望图像存储在 "#{RAILS_ROOT}/public/system/#{user.name}/#{user.album.name}/#{suffix}"

我设法改变了龙飞的root_path,我甚至覆盖了relative_storage_path,如下所示:

class MyDataStore < Dragonfly::DataStorage::FileDataStore
  private
   def relative_storage_path(suffix)
    "#{suffix}"
   end
end
Run Code Online (Sandbox Code Playgroud)

但尽管如此,我不知道我怎么可以通过ActiveRecord的对象属性,如user.nameuser.album.namerelative_storage_path 创建我的理想路径.

你知道我怎么做这样的事吗?

All*_*rgi 5

宝石作家马克埃文斯帮了我一个忙,并在谷歌小组回答了这个问题.以下是他的回答,对我的案例非常有用:

嗨,您好

你不能开箱即用,因为数据存储是有目的地设计的非常简单 - 你传入数据,它给你一个uid等.

如果你想这样做,你将不得不猴子补丁附件#save!像这样:

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
Run Code Online (Sandbox Code Playgroud)

我上面唯一改变的是datastore.store现在需要两个args.

然后你必须修改/ monkey-patch Dragonfly :: DataStorage :: FileDataStore#store以考虑第二个arg.

出于兴趣,为什么要将图像存储为该格式?

干杯马克

  • 现在不再需要以上答案,因为dragonfly现在支持自定义存储路径:http://markevans.github.com/dragonfly/file.Models.html#Storage_options (3认同)