【问题标题】:Carrierwave returns path of tmp file instead of actual in a callbackCarrierwave 在回调中返回 tmp 文件的路径而不是实际路径
【发布时间】:2016-09-15 14:57:08
【问题描述】:

在一个应用程序中,我想通过 after_create 回调将公共文件 URL 发送到服务。因此,代码(简化)如下所示:

class UserProfile < ApplicationRecord
  mount_uploader :video, VideoUploader
  after_create :send_url_to_service

  private

  # Just logs the URL
  def send_url_to_service
    Rails.logger.info video.url
  end
end

令我沮丧的是,在上传之后,send_url_to_service 回调总是记录缓存的文件路径——类似于'uploads/tmp/1473900000-123-0001-0123/file.mp4' 而不是'uploads/user_profiles/video/1/file.mp4'。我尝试编写一种方法来根据实际文件路径形成 URL,但由于文件尚不存在,因此无法正常工作。

那么,问题来了,在这种情况下,如何获取最终文件的 URL?

P. S. 请注意,这是一个自我回答的问题,我只是想分享我的经验。

【问题讨论】:

    标签: ruby-on-rails rails-activerecord carrierwave


    【解决方案1】:

    我的解决方案是使用after_commit ..., on: :create 回调而不是after_create

    class UserProfile < ApplicationRecord
      mount_uploader :video, VideoUploader
      after_commit :send_url_to_service, on: :create
    
      private
    
      # Just logs the URL
      def send_url_to_service
        Rails.logger.info video.url
      end
    end
    

    答案很明显,虽然我浪费了很长时间在它周围徘徊。解释很简单:after_commit 回调只有在所有信息都成功持久化后才会触发。在我的情况下,该文件尚未保存到存储目录(在after_create 阶段) - 这就是为什么我得到临时文件 url 而不是实际文件的原因。希望这可以帮助某人并节省他们的时间。

    【讨论】:

    • 使用带有 CarrierWave v2.0.3 的 rails 5.0.3,在将 after_create 更改为 after_commit 后,我仍然得到 tmp 路径。
    • 我也尝试调用reload - 但结果是文件根本没有保存
    猜你喜欢
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-28
    相关资源
    最近更新 更多