【问题标题】:Rails s3: Upload objects in a specific path depending on the ID of a modelRails s3:根据模型的ID在特定路径中上传对象
【发布时间】:2021-10-07 22:51:18
【问题描述】:

我有一个名为“CourseObjects”的模型,它属于另一个名为“Courses”的模型。

每门课程都有对象(视频、pdf、办公文件等)。我正在将这些元素从“CourseObjects”模型的形式上传到 S3,目前一切正常。如何在 s3 中为用户上传的每个“courseObject”创建一个路径,并保存在每个课程的特定 ID 中?

 class CourseObject < ActiveRecord::Base

    belongs_to :course


    has_attached_file :file,:storage => :s3,:bucket => 'demo-files',
                                             :path => "/capacitation/course_objects/(COURSE_ID)/content/:filename",
                                             :s3_credentials => {
                                                 :access_key_id => 'key',
                                                 :secret_access_key => 'secret_key'
                                             }

    validates_attachment_content_type :file,
                                                                        content_type: ['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'video/mp4', 'application/pdf', 'application/vnd.openxmlformats-officedocument.presentationml.presentation', :pptx]

end

【问题讨论】:

    标签: ruby-on-rails amazon-s3


    【解决方案1】:

    ActiveStorage 为自己的目的管理 blob 的命名(存储在 s3 中的内容),但您可以在附加文件时设置 filename 元数据;然后您可以稍后使用/搜索它。

    如果您已全局设置 s3 存储 (config/storage.yml),则无需使用 has_attached_file 再次声明服务,除非您覆盖环境的默认存储介质。

    class CourseObject < ActiveRecord::Base
        belongs_to :course
    
        has_attached_file :file
    end
    

    那么无论你在哪里附加文件:

    # 'file' is an IO object, UploadedFile, direct upload ref or whatever.
    course_obj.attach(file,     
                      filename: "/foo/#{course_obj.course.id}/bar/#{name}")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-03
      • 2017-08-24
      • 2018-12-03
      相关资源
      最近更新 更多