【问题标题】:Why is db:migrate failing when i try to add attachment fields for paperclip?当我尝试为回形针添加附件字段时,为什么 db:migrate 失败?
【发布时间】:2025-12-21 02:05:06
【问题描述】:

我正在尝试添加两个不同的附件字段。无论我是否使用捆绑程序运行它,迁移都会失败。 (bundle exec rake db:migrate 或只是 rake db:migrate)。

==  AddDiagramToQuestion: migrating ===========================================
-- change_table(:questions)
rake aborted!
An error has occurred, this and all later migrations canceled:

undefined method `has_attached_file' for #<ActiveRecord::ConnectionAdapters::Table:0x0000012b003b20>
 /Users/kboon/Documents/workspace/quiztaker/db/migrate/20111213182927_add_diagram_to_question.rb:6:in `block in up'
 /Users/kboon/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.1/lib/active_record/connection_adapters/abstract/schema_statements.rb:244:in `change_table'

迁移如下所示:

class AddDiagramToAnswer < ActiveRecord::Migration
  def self.up
    change_table :answers do |t|
      t.has_attached_file :diagram
    end
  end

  def self.down
    drop_attached_file :answers, :diagram
  end
end

该模型还引用了回形针添加的方法,并且应用程序运行良好,因此根本没有安装回形针。我什至尝试在迁移中添加 require 'paperclip' ,但这根​​本没有帮助。

【问题讨论】:

  • 是您Gemfile 中的回形针宝石吗?
  • 是的,我应该明确地说出来。 has_attached_file 在我的模型中也可以正常工作
  • 你用的是什么版本的回形针?
  • 错误是20111213182927_add_diagram_to_question.rb:6,但您发布的迁移是针对answers 而不是questions。您是否在此处发布了正确的迁移文件?
  • 一种解决方法是使用rails g paperclip question diagram生成的显式迁移。

标签: ruby-on-rails ruby-on-rails-3.1 paperclip


【解决方案1】:

为我创建的迁移不再使用 t.has_attached_file 术语,它实际上显式添加了列。将通过运行以下命令创建迁移:

rails generate paperclip Answer diagram

查看示例here

【讨论】:

  • 尽管文档仍然使用 has_attached_file 方法,但我最终还是这样做了。
【解决方案2】:

这对我有用

def change
  create_table :some_table do |t|
    t.attachment :avatar
    t.timestamps
  end
end

【讨论】:

    【解决方案3】:

    迁移文件应该是这样的

    class AddDiagramToAnswer < ActiveRecord::Migration
      def self.up
        add_attachment :answers, :diagram
      end
    
      def self.down
        remove_attachment :answers, :diagram
      end
    end
    

    class AddDiagramToAnswer < ActiveRecord::Migration
      def change
        create_table :users do |t|
          t.attachment :avatar
        end
      end
    end
    

    has_attached_file 用于 model.rb(answer.rb in your app)

    带导轨 5

    【讨论】:

      最近更新 更多