Sylar
Sylar

Reputation: 12072

Rails 4: Add Column To An Existing Scaffold

Yes, this question is flooded on here but most are few years back and I am using Rails 4. I have tried few and it messed up my rails app so I wont take anymore chances.

I have already created a scaffold with fields and I have made many changes to its model, controller and views. Imagine you are working for someone when few weeks later, after you've created a scaffold, they realized they missed out an important column - lol

rails g scaffold Book a:string b:integer

How do I easily add c:date?

Few examples showed running a migration and few says edit the rails console. I am confused with the rails g migration add_this_to_that c:data??

Any reference with your answer is highly appreciated as I'm still learning RoR.

Upvotes: 3

Views: 8800

Answers (1)

Rustam Gasanov
Rustam Gasanov

Reputation: 15781

To add new column, you should create migration:

rails g migration add_c_to_books c:date

(note the syntax: add_x_to_y), which will add this file to db/migrate/timestamp_add_c_to_books.rb:

class AddCToBooks < ActiveRecord::Migration
  def change
    add_column :books, :c, :date
  end
end

Now all you need is to run it with:

rake db:migrate

That's it.


You can add multiple columns with:

rails g migration add_c_d_e_to_books c:date d:string e:integer

Which will create following migration:

class AddCDEToBooks < ActiveRecord::Migration
  def change
    add_column :books, :c, :date
    add_column :books, :d, :string
    add_column :books, :e, :integer
  end
end

Or name it however you want:

rails g migration my_migration

Which will result in clean migration:

class MyMigration < ActiveRecord::Migration
  def change
  end
end

You are free to specify your directives inside def change.

Upvotes: 8

Related Questions