【发布时间】:2018-12-29 09:34:16
【问题描述】:
我目前正在使用this 教程从Paperclip 迁移到Active Storage,以及参考官方guide。
当前的障碍是migrating my assets 的 rake 任务。
这是我的lib/tasks/migrate_paperclip_assets.rake文件的内容:
desc 'Generates file names on AWS S3 and places them in their proper structure'
namespace :posts do
task migrate_to_active_storage: :environment do
Post.where.not(image_file_name: nil).find_each do |post|
img_filename = post.image_file_name
ext = File.extname(img_filename)
image_url =
"https://#{Rails.application.credentials.dig(:aws,
:bucket_name)}/#{Rails.application.credentials.dig(:aws,
:host_name)}/posts/images/000/000/#{post.id}/original/#{img_filename}"
puts image_url
post.image.attach(io: open(image_url),
filename: post.image_file_name,
content_type: post.image_content_type)
end
end
end
当我运行它时,我收到以下错误:
rake aborted!
NoMethodError: undefined method `attach' for #<Paperclip::Attachment:0x00000003170090>
[...]
在 Rails 迁移指南中,它明确指出使用此方法附加 here,格式与我所做的相同 - 不知道为什么会出现错误。我确定该网址有效,并且我已成功尝试下载图片。
以下是我尝试过但不起作用的方法:
- 已尝试this accepted solution。
- 我从the docs 看到的最接近附件的是
assign方法。但是没有处理图像文件的处理程序。 - 我也尝试过下载同一目录中的文件并使用相同的
post.image.attach上传它们。
尽管 Paperclip Attachment Class 本身没有定义 attach 方法,但 GitHub 上有大量代码具有类似格式的代码:
user.avatar.attach(io: open(avatar_url), filename: user.avatar_file_name).
这是我的app/models/post.rb文件的内容:
class Post < ApplicationRecord
belongs_to :user
has_many :comments, dependent: :destroy
has_many :likes, dependent: :destroy
has_many :dislikes, dependent: :destroy
attr_accessor :uploaded_image_for_io_adapters, :file_name, :top_text, :bot_text
has_attached_file :image
validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/
validates_attachment :image, presence: true
validates_presence_of :poster
validates_presence_of :description
validates :user, presence: true
validates :user_id, presence: true
end
迷失和困惑,如果你能建议一个替代方法来绕过必须使用这个attach 方法,或者给我指点我可能做错了什么,那就太好了。
对于上下文,Ruby 版本:2.4.1,Rails:5.2.1
【问题讨论】:
标签: ruby-on-rails paperclip rails-migrations rails-activestorage