Rails: Modifying a Model Generated by Scaffolding

2019-01-31 17:20发布

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.

3条回答
啃猪蹄的小仙女
2楼-- · 2019-01-31 17:59

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)

查看更多
我想做一个坏孩纸
3楼-- · 2019-01-31 18:02
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.

查看更多
4楼-- · 2019-01-31 18:03

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

查看更多
登录 后发表回答