0

For example, I have a migration file for posts:

class CreatePosts < ActiveRecord::Migration
  def change
    create_table :posts do |t|
      t.text :text
      t.integer :ip

      t.timestamps
    end
  end
end

And want to change it to:

class CreatePosts < ActiveRecord::Migration
  def change
    create_table :posts do |t|
      t.text :text
      t.integer :ip, :limit => 8

      t.timestamps
    end
  end
end

Would I add a line:

change_column :posts, :ip, :limit => 8

Below so that the file is:

class CreatePosts < ActiveRecord::Migration
  def change
    create_table :posts do |t|
      t.text :text
      t.integer :ip, :limit => 8

      t.timestamps
      change_column :posts, :ip, :limit => 8
    end
  end
end

And then run heroku run rake --trace db:migrate

I'm having trouble understanding how migrations work, and especially to production, so any help would be greatly appreciated.

There is http://guides.rubyonrails.org/active_record_migrations.html#changing-columns a section 3.5 on column modifiers but it doesn't specify how to pass them.

Thanks!

1
  • Oh except in the final example would it read t.integer :ip and then only below would the limit be set in the change_column? Thanks! Commented Feb 8, 2015 at 3:04

1 Answer 1

1

You should create a separate migration for adding the limit on the ip column.

Generate your migration:

rails generate migration ChangeIpLimitOnPosts

Inside the generated migration file, update the contents:

class ChangeIpLimitOnPosts < ActiveRecord::Migration
  def up
    change_column :posts, :ip, :integer, limit: 8
  end

  def down
    change_column :posts, :ip, :integer
  end
end

Take note here: you need to specify the column type when changing the column, even though in your case, you're not changing the type.

Also, in this case, Active Record will not know how to reverse the transaction if you need to rollback, so you need to explicitly tell Active Record how to do that — this can be done using the up and down methods, rather than change.

Run your migration:

rake db:migrate

On Heroku:

heroku run rake db:migrate

Hope that helps.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah I almost got here but missed that I have to re-specify integer type, can't just pass a modifier. Anyway, fantastic to have applied a working example so that I actually have some intuitive understanding of migrations now, changing their status from one of the banes of my existence to pretty okay :P Thanks so much Jordan!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.