Ruby-on-rails Rails:修改由脚手架生成的模型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/530842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails: Modifying a Model Generated by Scaffolding
提问by Andrew Hampton
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.
您如何修改使用建模生成的模型?例如,模型 myModel 最初有 a、b 和 c 列,但我现在想添加列 d。
回答by BookOfGreg
Rails 3 and above use the following code :
Rails 3 及更高版本使用以下代码:
rails generate migration add_fieldname_id_to_tablename fieldname:string
Rails 2
导轨 2
ruby script/generate migration add_fieldname_to_tablename fieldname:string
This no longer works and returns the following error in Rails 3:
这不再有效并在 Rails 3 中返回以下错误:
ruby: No such file or directory -- script/generate (LoadError)
ruby: 没有这样的文件或目录——脚本/生成 (LoadError)
回答by Luke
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.
这是做你想做的事的捷径。如果您需要更多控制,或者要添加很多列,Andrew H 的回答也可以。
回答by Andrew Hampton
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:
然后编辑位于 db/migration 中的新迁移文件,如下所示:
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
表函数在这里找到

