我正在嘗試從我的 Rails 應用程式(7.0.1)、Ruby(3.0.2)發推文。我正在使用“twitter” gem 和其他人連接 Twitter 帳戶并發布到 Twitter。只要我只發推文,一切都很好。文本來自“Model.content”。
還有另一個“Model.media”是一個帶有“has_one_attached”的附件,我想用它來將媒體上傳到 Twitter。它存盤在 AWS S3 中。
這是使用 gem 發布文本的方法(只是“內容”而不是“Model.content”,因為我是從 Model.rb 本身發布推文):
client.update(content)
它可以正常作業并在 Twitter 上發布。
要通過媒體發布推文,我可以根據 gem 這樣做:
client.update_with_media(content, media)
我從 Rails 日志中得到的錯誤是:
/Users/~/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/activesupport-7.0.1/lib/active_support/core_ext/module/delegation.rb:307:in `method_missing': undefined method `merge' for #<ActiveStorage::Attached::One:0x00007fca71579048 @name="media", @record=#<...">> (NoMethodError)
如果我試試這個:
client.update_with_media(content, Rails.application.routes.url_helpers.rails_blob_path(media, only_path: true))
我從 Rails 日志中得到的錯誤是(.jpeg 也是如此):
/Users/~/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/twitter-7.0.0/lib/twitter/rest/upload_utils.rb:40:in `append_media': undefined method `eof?' for "/rails/active_storage/blobs/redirect/....mp4":String (NoMethodError)
我嘗試并尋找了許多解決方案,如果我理解正確,它們并不是專門針對這個問題的。我覺得我錯過了一件非常小的事情。
解決此問題的最佳方法是什么以及如何?
鏈接:寶石鏈接:https ://rubygems.org/gems/twitter
Gem 快速指南:https ://github.com/sferik/twitter/blob/master/examples/Update.md#update
uj5u.com熱心網友回復:
根據檔案,media必須是一個File或一個 s 陣列File。此方法不支持直接上傳,因此您必須先從 S3 下載檔案,然后再將其上傳到 Twitter。
rails_blob_path回傳一個字串,這就是它不起作用的原因。此外,此路徑與您的應用程式域相關,因此您不能直接使用它來參考檔案系統上的檔案。
ActiveStorage 有一個open方法可以產生一個Tempfile. 幸運的是,它們的行為與常規Files 一樣,因此您應該能夠將其傳遞給update_with_media. 你可以像這樣使用它:
media.open do |file|
client.update_with_media(content, file)
end
它將在檔案系統上創建一個臨時檔案。
或者,如果您的檔案相對較小(視頻可能不是這種情況),您可以使用該download方法。它將下載檔案并將其存盤在記憶體中:
client.update_with_media(content, media.download)
旁注:POST update_with_media 已棄用,不應再使用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/430942.html
