如何从 Rails 控制台附加本地硬盘的 Active Storage 映像?

use*_*745 14 ruby-on-rails rails-activestorage

我正在尝试学习如何将本地硬盘中的图像附加到 Active Storage。例如

User.last.images.attach("../../Downloads/me.jpg")
Run Code Online (Sandbox Code Playgroud)

但我看到

ActiveSupport::MessageVerifier::InvalidSignature: ActiveSupport::MessageVerifier::InvalidSignature
from /Users/st/.rbenv/versions/2.7.1/lib/ruby/gems/2.7.0/gems/activesupport-6.0.3.2/lib/active_support/message_verifier.rb:176:in `verify'
Run Code Online (Sandbox Code Playgroud)

use*_*745 20

问题是您不应该只提供文件路径,而应该提供文件路径File.open()(错误消息不一定使这一点显而易见)。

一旦解决了,filename还必须提供 a,所以完整的答案是:

User.last.images.attach(io: File.open("../../Downloads/me.jpg"), filename: "something")
Run Code Online (Sandbox Code Playgroud)

注意:另一位用户提供了更通用的方法:

User.last.images.attach(io: File.open("#{Rails.root}/app/assets/images/my_image.png"), filename: 'my_image.png', content_type: 'image/png')
Run Code Online (Sandbox Code Playgroud)