Mongo对象的ID在CarrierWave中作为uploadings dirname

时间:2014-05-13 03:52:30

标签: ruby mongodb sinatra mongoid carrierwave

我使用Sinatra与Mongoid和CarrierWave。我需要在 / public / attachments / DOCUMENTS_ID 中存储文档的附件。

Mongo文档模型:

class Dcmnt
  include Mongoid::Document
  store_in collection: 'dcmnts'
  field :published,   type: Boolean
  field :name,        type: String
  field :description, type: String
  field :additional,  type: String
  field :created_at,  type: Date
  mount_uploader :attachment, Uploader, type: String
end

动作的代码:

  post '/admin/create' do
    params.delete 'submit'
    d = Dcmnt.new(
      :published   => params[:published],
      :name        => params[:name],
      :description => params[:description],
      :additional  => params[:additional],
      :created_at  => Time.now
    )
    d.attachment = params[:photos]
    d.save
  end

当我像这样设置卸载程序时:

class Uploader < CarrierWave::Uploader::Base
  storage :file
  def store_dir
    'public/attachments/' + d.id
  end
end

它不适用于某些 amzaing 的原因。你能帮我实现这个功能吗?

1 个答案:

答案 0 :(得分:1)

通过 model 关键字提供访问CarrierWave中的模型属性

class Uploader < CarrierWave::Uploader::Base
  storage :file
  def store_dir
    'attachments/' + model.id
  end
end