首页
/ Mongoid::Paperclip 技术文档

Mongoid::Paperclip 技术文档

2024-12-20 11:14:39作者:瞿蔚英Wynne

1. 安装指南

首先,确保您的项目已经集成了 Mongoid 作为 ODM(对象文档映射)。接下来,您需要在 Gemfile 中添加以下依赖:

gem "mongoid-paperclip"

完成依赖添加后,运行以下命令安装 gem:

bundle install

2. 项目的使用说明

基本使用

假设我们有一个 User 模型,并希望允许用户上传头像。以下是如何在模型中集成 Mongoid::Paperclip

class User
  include Mongoid::Document
  include Mongoid::Paperclip

  has_mongoid_attached_file :avatar
end

现在,用户可以上传头像了。与 ActiveRecord 不同,Mongoid 不使用迁移,因此不需要在单独的文件中定义 Paperclip 的列。调用 has_mongoid_attached_file 将自动为您定义所需的 :avatar 字段。

复杂示例

Mongoid::Papercliphas_mongoid_attached_file 方法接受第二个参数(选项的哈希),因此您可以进行更复杂的事情,如下所示:

class User
  include Mongoid::Document
  embeds_many :pictures
end

class Picture
  include Mongoid::Document
  include Mongoid::Paperclip

  embedded_in :user, :inverse_of => :pictures

  has_mongoid_attached_file :attachment,
    :path           => ':attachment/:id/:style.:extension',
    :storage        => :s3,
    :url            => ':s3_alias_url',
    :s3_host_alias  => 'something.cloudfront.net',
    :s3_credentials => File.join(Rails.root, 'config', 's3.yml'),
    :styles => {
      :original => ['1920x1680>', :jpg],
      :small    => ['100x100#',   :jpg],
      :medium   => ['250x250',    :jpg],
      :large    => ['500x500>',   :jpg]
    },
    :convert_options => { :all => '-background white -flatten +matte' }
end

注意事项

如果您计划保存或更新父文档,您必须在 embeds_XXX 语句中添加 cascade_callbacks: true。否则,您的数据将被更新,但 Paperclip 函数将不会运行来复制/更新您的文件。

3. 项目API使用文档

Mongoid::Paperclip 提供了以下方法来处理文件附件:

  • has_mongoid_attached_file:定义附件字段及其选项。
  • disable_fingerprint:禁用文件的指纹计算。

更多详细信息,请参考官方文档。

4. 项目安装方式

项目的安装方式已在“安装指南”中详细介绍。确保按照以下步骤操作:

  1. 在 Gemfile 中添加 mongoid-paperclip 依赖。
  2. 运行 bundle install 命令安装 gem。
  3. 在模型中使用 Mongoid::Paperclip

以上步骤将帮助您成功集成 Mongoid::Paperclip 到您的项目中。

登录后查看全文
热门项目推荐