Mani
Mani

Reputation: 2563

Data too long for column - Rails 4 migrations cancelled

I made a migration initially as below

class Createfriends < ActiveRecord::Migration
  def change
    create_table :friends do |t|
      t.string :FirstName
      t.string :LastName
      t.string :MiddleName
      t.string :Gendre
      t.string :Email
      t.string :ImageUrl
      t.string :Country
      t.string :City
      t.timestamps null: false
    end
  end
end

Then i need to change the type of ImageUrl as someone can load send the path of link which may exceed 255 characters so i made another migration as below

class ChangeImageUrlInWaiter < ActiveRecord::Migration
  def up
    change_column :friends, :ImageUrl , :text
  end

  def down
    change_column :friends ,:ImageUrl , :string
  end
end

Now when I try to rollback all migrations using

rake db:migrate VERSION=0

It throws me error

rake aborted! StandardError: An error has occurred, all later migrations canceled:

Mysql2::Error: Data too long for column 'ImageUrl' at row 1: ALTER TABLE waiters CHANGE ImageUrl ImageUrl varchar(255) DEFAULT NULL

Reason is clear that There is data present in ImageUrl which is more than 255 , Now the question is how to overcome this problem saving the data or even if have to loss some of data

Upvotes: 1

Views: 502

Answers (1)

Aleksey Shein
Aleksey Shein

Reputation: 7482

If you're ok with truncating your data, then just issue an UPDATE query before changing the schema back to 255 chars.

Don't use ActiveRecord in migrations, it's hard to get it right and may bring you different types of issues. So, you need this:

  def down
    execute 'UPDATE friends SET ImageUrl = SUBSTR(ImageUrl, 1, 255)'
    change_column :friends, :ImageUrl, :string
  end

Upvotes: 4

Related Questions