我目前正在使用this教程以及参考官方guide从Paperclip迁移到Active Storage。
当前的障碍是migrating my assets的瑞克任务。
这是我的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-不知道为什么会产生错误。我肯定知道该网址可以正常工作,并且已经成功尝试下载图像。
以下是我尝试过的无效的方法:
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
答案 0 :(得分:0)
我认为解决方案在documentation you have shared中。
class Organization < ApplicationRecord
# New ActiveStorage declaration
has_one_attached :logo
# Old Paperclip config
# must be removed BEFORE to running the rake task so that
# all of the new ActiveStorage goodness can be used when
# calling organization.logo
has_attached_file :logo,
path: "/organizations/:id/:basename_:style.:extension",
default_url: "https://s3.amazonaws.com/xxxxx/organizations/missing_:style.jpg",
default_style: :normal,
styles: { thumb: "64x64#", normal: "400x400>" },
convert_options: { thumb: "-quality 100 -strip", normal: "-quality 75 -strip" }
end
似乎has_attached_file
必须替换为has_one_attached
。
否则,image
将使用Paperclip而不是ActiveStorage(具有attach
方法的ActiveStorage)。