Home Ask Login Register

Developers Planet

Your answer is one click away!

Spance February 2016

Rails - renaming a column and then migrating

Preface: I'm pretty new to Ruby/Rails

So I have a column in my 'Invitations' table called "name" and I wanted to rename it to "team_name." I changed that in my migrate file, then did a rollback, then re-ran migrate.

class CreateInvitations < ActiveRecord::Migration
  def change
    create_table :invitations do |t|
      t.string :token
      t.string :team_name
      t.integer :number_of_uses
      t.timestamps null: false

This is what my schema looks like now:

create_table "invitations", force: :cascade do |t|
    t.string   "token"
    t.string   "team_name"
    t.integer  "number_of_uses"
    t.datetime "created_at",     null: false
    t.datetime "updated_at",     null: false

Then I went and changed all the instances of 'name' to 'team_name' but now I'm getting all sorts of errors. For example,

class Invitation < ActiveRecord::Base
  has_and_belongs_to_many :users

  validates :team_name, presence: true

With the spec,

describe '#team_name' do
    it { should validate_presence_of :team_name }

And rspec failure,

5) Invitation#team_name should require team_name to be set
     Failure/Error: it { should validate_presence_of :team_name }
       undefined method `team_name=' for #<Invitation:0x007fd39a26def8>
     # ./spec/models/invitation_spec.rb:7:in `block (3 levels) in <top (required)>'

Almost all the errors I'm getting are exactly like this one. I made sure to include the change in my Factory as well...I'm not sure what is really going on here. Did I make a mistake when I changed the column name and did another migrate? Again, I'm still learning Rails. Appreciate the help, thanks.


Thomas Haratyk February 2016

The testing environment use its own database schema. Make sure you update your test database as well :

bundle exec rake db:test:prepare

Elton Santos February 2016

You can change the migration file name, but you have to perform a few steps:

  1. rake db:rollback to the point that queries table is rolled back.
  2. Now change the name of migration file, also the contents.
  3. Change the name of any Model that may use the table.
  4. rake db:migrate

Post Status

Asked in February 2016
Viewed 1,825 times
Voted 5
Answered 2 times


Leave an answer

Quote of the day: live life