24

How do you modify a model you've generated using modeling? For example, the model myModel originally had columns a, b and c, but I now want to add column d.

Andrew Hampton
  • 1,632
  • 3
  • 20
  • 29

3 Answers3

25

Rails 3 and above use the following code :

rails generate migration add_fieldname_id_to_tablename fieldname:string

Rails 2

ruby script/generate migration add_fieldname_to_tablename fieldname:string 

This no longer works and returns the following error in Rails 3:

ruby: No such file or directory -- script/generate (LoadError)

BookOfGreg
  • 3,550
  • 2
  • 42
  • 56
  • Thanks, would be nice to strike out the non-working combination, though, it confuses a bit... Or may be make some kind of headers (Rails <= 2, Rails >= 3 for example) . – Wiseman Jan 27 '15 at 08:05
  • Thanks Wiseman, just edited to take that into account, is that better? – BookOfGreg Jan 27 '15 at 16:17
19
ruby script/generate migration add_fieldname_to_tablename fieldname:string

this is the shortcut method to do exactly what you want. if you need more control, or if you have a lot of columns to add, Andrew H's answer will work fine too.

Luke
  • 2,977
  • 1
  • 20
  • 15
13

The best answer I've found so far is run this from your project root:

ruby script/generate migration add_d_column_to_myModel 

Then edit the new migration file located in db/migration to look something like:

  def self.up
    add_column :myModel, :d, :string
  end

  def self.down
    remove_column :myModel, :d
  end

The last step will be to update your views accordingly.

Answer found here

Table functions found here

Andrew Hampton
  • 1,632
  • 3
  • 20
  • 29
  • Confused--why did you ask the question if you had a good answer? Why not post this in the original question and ask for better solutions? – zenazn Feb 10 '09 at 02:10
  • 1
    I think you answered your own question. One thing I will say, however, is that in some case you can edit the model migration directly. Migrations are great when you have a site in production, but for ongoing development, you often have the luxury of blowing away the DB and starting again. – Toby Hede Feb 10 '09 at 02:12
  • 2
    I answered my own question for 2 reasons. First, this was the best answer I found, but I'm new to Rails and thought there may be a better way I didn't find. Second, the Question hadn't been posted on StackOverflow, so I decided to add it. – Andrew Hampton Feb 10 '09 at 11:51
  • 3
    I am glad you answered your own question. Lots of people probably have similar questions. – Drew LeSueur Dec 12 '10 at 02:22