从命令行编辑 Rails 模型
我对 Ruby on Rails 还很陌生,我想知道是否有一种方法可以编辑模型的数据库架构。
例如,我的应用程序中有订阅者模型 - 我创建它的方式是使用rails生成脚手架订阅者电子邮件:字符串
但是现在,我也想在订阅者模型中拥有一个名称。有什么简单的方法可以做到这一点吗?我已经在当前的控制器和视图中放入了大量代码,因此我不一定要销毁脚手架,但我想编辑模型。
预先感谢
hwrd
, 我正在使用 Ruby on Rails 3
I am pretty new to Ruby on Rails, and I was wondering if there was a way to edit the database schema for a model.
For example, I have the Subscriber model in my application -- the way I created it was by using rails generate scaffold Subscriber email:string
But now, I want a name in the subscriber model as well. Is there any easy way to do this? I have put a lot of code in my current controllers and views, so I don't necessarily want to destroy the scaffold, but I would like to edit the model.
Thanks in advance,
hwrd
P.S. I am using Ruby on Rails 3
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
ActiveRecord 模型检查它所代表的表。您实际上不需要仅仅为了添加新字段而更改模型(除非您想添加验证等)。
您要做的是进行新的迁移,然后向上迁移数据库:
然后您可以开始在控制器和视图中引用名称字段。
(这个生成器命令可能看起来有点神奇,但是 Rails 生成器可以识别这种格式,并将生成适当的
add_column
和remove_column
代码。请参阅 Rails 迁移指南以供进一步阅读。)An ActiveRecord Model inspects the table it represents. You don't actually need to change your model just to add a new field (unless you want to add validations, etc).
What you want to do is make a new migration and then migrate your database up:
Then you can start referencing the name field in your controllers and views.
(This generator command might seem a little magical, but the rails generator recognizes this format and will generate the appropriate
add_column
andremove_column
code. See the Rails migration guide for further reading.)如果您的意思是更改模型的数据库架构,您将需要使用迁移。
您将执行类似
http://guides.rubyonrails.org/migrations.html
的操作,如果您仅意味着查找模型并更新每个实例内的数据,请遵循 @apneadiving 的答案。
If you mean changing the database schema of your model, you'll want to use migrations.
You'll do things like
http://guides.rubyonrails.org/migrations.html
If you do only mean finding models and updating the data inside each instance, go with @apneadiving's answer.