wuyuedefeng / blogs

博客文章在issue中
5 stars 0 forks source link

Rails active_storage集成阿里云oss #57

Open wuyuedefeng opened 4 years ago

wuyuedefeng commented 4 years ago

默认storage以文件的形式存在服务器中

local: service: Disk root: <%= Rails.root.join("storage") %>

aliyun: service: Aliyun access_key_id: "LTAIwdxxxxxxxx" access_key_secret: "juYPTswGjxxxxxxxxxxxxxxx" bucket: "xxxx" endpoint: "https://oss-cn-hangzhou.aliyuncs.com"

path prefix, default: /

path: "moon"

Bucket mode: [public, private], default: public

mode: "public"

配置`production`环境使用阿里云存储, 需修改环境配置文件`config/enviroments/production.rb`
```ruby
 # config.active_storage.service = :local
 config.active_storage.service = :aliyun

eg: model feedback.rb

class Feedback < ApplicationLogsRecord
  # belongs_to :trackable, polymorphic: true, optional: true
  # belongs_to :actorable, polymorphic: true, optional: true
  # belongs_to :application, class_name: 'Doorkeeper::Application'
  has_one_attached :image
end

usage, eg:

Feedback.create.attach(params[:signed_id])

eg: model feedback.rb

class Feedback < ApplicationLogsRecord
  # belongs_to :trackable, polymorphic: true, optional: true
  # belongs_to :actorable, polymorphic: true, optional: true
  # belongs_to :application, class_name: 'Doorkeeper::Application'
  has_many_attached :images
end

usage, eg:

Feedback.create(images: params[:signed_ids])
wuyuedefeng commented 4 years ago

gem reform更新attachment

app/forms/reform_base.rb

class ReformBase < Reform::Form
  # https://edgeguides.rubyonrails.org/active_storage_overview.html
  def attach_file property
    if self.try(property).present?
      self.model.try(property).attach self.try(property)
    elsif self.model.try(property).try(:attached?)
      self.model.try(property).purge_later
    end
    true
  end
end

has_one_attached :image

app/forms/api/banner_form/create.rb

module BannerForm
  class Create < ReformBase
    model :banner

    property :image, virtual: true # signed_blob_id
    validates :image, presence: true

    def save
      attach_file :image if super
    end

  end
end

app/forms/api/banner_form/update.rb

module BannerForm
  class Update < ReformBase
    model :banner

    property :image, virtual: true # signed_blob_id
    validates :image, presence: true

    def save
      attach_file :image if super
    end

  end
end

has_many_attached :images

module Api::FeedbackForm
  class Create < ReformBase
    model :feedback

    property :images # 直接将signed_ids数组赋值给images即可,更新也是一样
  end
end