如何获取当前的 Mongoid 会话或数据库

How to get the current Mongoid session or database

我有一个多租户应用程序,我使用 Mongoid.override_session(current_user.customer_id) 指向适当的客户数据库。我正在使用回形针将照片保存到 S3 存储桶,我希望文件夹结构以 customer_id 开头,但我找不到从 Mongoid 获取当前会话或数据库的方法。我找到了 this question,但答案在 Mongoid v4.0.1 上对我不起作用。 current_user 超出了为回形针设置 URL 的模型代码的范围,回形针初始值设定项也是如此。

如果它对其他人有帮助,我发现这是一种方法,您可以在 class 或模型实例

上 运行
mongo_session.options[:database]

我在回形针初始化器中添加了以下内容;

#myapp/config/initializer/paperclip.rb  
Paperclip.interpolates :customer_id do |attachment, style|
  attachment.instance.mongo_session.options[:database]
end

然后你可以在你的模型中引用:customer_id

has_mongoid_attached_file :image,
                            :storage => :s3,
                            :s3_credentials => File.join(Rails.root, 'config', 'aws.yml'),
                            :styles => {
                                :medium => '600x600>',
                                :small => '300x300>',
                                :thumb => '100x100>'
                            },
                            :path => ':customer_id/:style/:filename',
                            :url => '/:customer_id/:style/:filename'