Kyle Boon
Kyle Boon

Reputation: 5231

Why is db:migrate failing when i try to add attachment fields for paperclip?

I am trying to add two different attachment fields. The migration is failing wether i run it using bundler or without. (bundle exec rake db:migrate or just 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'

The migration looks like this:

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

The model also references methods added by paperclip and the app runs fine so its not that paperclip isn't installed at all. I've even tried added require 'paperclip' to the migration but that didn't help at all.

Upvotes: 8

Views: 10118

Answers (3)

Nyein
Nyein

Reputation: 286

Migration file should be look like

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

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

or

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

has_attached_file is used in model.rb(answer.rb in your app)

with rails 5

Upvotes: 2

jmosesman
jmosesman

Reputation: 726

This worked for me

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

Upvotes: 2

andrew.rockwell
andrew.rockwell

Reputation: 641

The migration that was created for me doesn't use the t.has_attached_file terminology anymore, it actually adds the columns explicitly. The migration would be created by running:

rails generate paperclip Answer diagram

Check out the example here.

Upvotes: 11

Related Questions