【问题标题】:Update attachment Rails Active Storage更新附件 Rails Active Storage
【发布时间】:2020-11-04 08:21:42
【问题描述】:

我有一个由 Rails API 支持的 React 前端,我通过 Active Storage 将照片发送到 Cloudinary。我的设置是标准的:我有一个带有 has_one_attached :photo 方法的 Event 模型,而 POST 端点“/api/v1/events”由带有简单 @event = Event.new(event_params) 的“Events#create”方法提供服务。我还在“事件”表中保存了一个额外的“url”列,以便在需要时将其显示回来(我用@event.photo.url 得到它(警告说“service_url”据说已贬值)。我可以获取它(浏览器的 fetch api)并在 React 中使用它。这行得通。

当我编辑表单并使用新照片提交表单时,我必须使用以下 events#update 方法调整 PATCH 查询。我按照 Rails 指南说你应该 purgecreate_and_upload!

def update
    @event = Event.find(params[:id])
    logger.debug "..................BEFORE : ..#{@event.to_json}"
    if event_params[:photo] || @event.url
      @event.photo.purge
      @event.url = nil
    end    
    if @event.update(event_params)
      if event_params[:photo]
        ActiveStorage::Blob.create_and_upload!(
          io: File.open(event_params[:photo].tempfile),
          filename: event_params[:photo].original_filename,
          content_type:event_params[:photo].content_type
        )
        @event.url = @event.photo.url
      end
      logger.debug "................AFTER :.. #{@event.to_json}"
      render json: {status: :ok}
    else
      render json: {errors: @event.errors.full_messages},
        status: :unprocessable_entity, notice:"not authorized"
    end
end

我的日志显示这会产生一个 url,但没有 url 发送到 React。如果我修改此表单中的其他字段,我会从 Rails 中获取 React 中的更新。但是,未发送链接:url: null。 我什至不使用 Active Job,但使用 6.03 甚至更新到 6.1。有人经历过吗?

FI,params 哈希包含以下内容:

"photo"=>#<ActionDispatch::Http::UploadedFile:0x00007fd938f1ecf8 @tempfile=#<Tempfile:/var/folders/11/whcyvzvx3w54zb0n1r0929200000gn/T/RackMultipart20200714-79173-t9s624.svg>, @original_filename="Rafting.svg", @content_type="image/svg+xml", @headers="Content-Disposition: form-data; name=\"event[photo]\"; filename=\"Rafting.svg\"\r\nContent-Type: image/svg+xml\r\n">}

【问题讨论】:

    标签: ruby-on-rails reactjs


    【解决方案1】:

    如果有任何兴趣,我找到了有关如何更新 Active Storage 的答案。我的模型是Event,其列url 包含一个Cloudinary 链接,附加的活动存储对象名为photo)。然后在PATCH 上,如果需要,首先是purge,然后使用.url(以前的.service_url)方法更新event.url 列:

    event.update(url: event.photo.url)

    def update
        event = Event.find(params[:id])
    
        # purge if a link already exists and the params contain a new picture
        if event_params[:photo] && event.url
          event.photo.purge
        end
    
        if event.update(event_params)
          if event_params[:photo]
            event.update(url: event.photo.url)
          end
          render json: event, status: :ok
        else
          render json: {errors: event.errors.full_messages},
            status: :unprocessable_entity, notice:"not authorized"
        end
      end
    

    Rails 指南似乎具有误导性..

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-01
      • 2019-08-16
      • 1970-01-01
      • 1970-01-01
      • 2018-10-24
      • 2022-11-28
      • 2020-09-03
      • 2019-09-17
      相关资源
      最近更新 更多