首页 > 解决方案 > Paperclip::Attachment - 未定义的方法“附加”。资产迁移耙任务

问题描述

我目前正在使用教程从 Paperclip 迁移到 Active Storage,并参考官方指南

当前的障碍是迁移我的资产的 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 迁移指南中,它清楚地说明了在此处以与我所做的相同格式使用此方法附加 - 不知道为什么会出现错误。我确定该网址有效,并且我已成功尝试下载图像。

以下是我尝试过但不起作用的事情:

  1. 尝试了这个公认的解决方案
  2. 我从文档中看到的最接近的附件是assign方法。但是没有处理图像文件的处理程序。
  3. 我也尝试在同一目录中下载文件并使用相同的post.image.attach.

尽管Paperclip 附件类本身没有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-railspapercliprails-migrationsrails-activestorage

解决方案


我认为解决方案在您共享的文档中

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方法)。


推荐阅读