在 Ruby on Rails 中更改数据库列的命令
是否有一个可以运行的快速控制台命令来更改对象的类型?它目前是 Ruby Date 类型,但我希望它是 Ruby Time 类型。
我从这个脚手架命令开始:
$ rails generate scaffold Post title:string content:text postdate:date
但希望我会执行以下操作:
$ rails generate scaffold Post title:string content:text postdate:time
是否有命令并且可以运行来进行更新?
Is there a quick console command I can run to change the type I have for an object? It's currently a Ruby Date type, but I would like it to be a Ruby Time type.
I started with this scaffold command:
$ rails generate scaffold Post title:string content:text postdate:date
But wish I would have done the following:
$ rails generate scaffold Post title:string content:text postdate:time
Is there a command and can run to make the update?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有时您必须编写一些实际代码,即使是在 Rails 中也是如此。尝试创建迁移,然后使用
change_column
方法。就像你把它放在你的数据库迁移文件中,而不是放在 shell 中。
Sometimes you have to write some actual code, even in Rails. Try creating migration and then using
change_column
method. Something likeYou put this in your db migration file, not in shell.
如果您不希望错误成为迁移集中的永久部分,只需向下迁移 (
rake db:rollback
),编辑迁移文件,然后向上迁移 (rake db :迁移
)。编辑:回答你关于只有一个命令的问题?是的,有。编辑迁移后:
只需一个命令即可运行“down”,然后运行“up”。
If you don't want the mistake to be a permanent part of the migration set, simply migrate down (
rake db:rollback
), edit your migration file, and migrate back up (rake db:migrate
).Edit: To answer your question about there being a single command? Yes, there is. After editing your migration:
This runs the "down" followed by the "up" in just one command.
更改列类型的三个步骤:
步骤 1:
使用此代码生成新的迁移文件:
步骤 2:
转到
/db/migrate
文件夹并编辑您创建的迁移文件。有两种不同的解决方案。2.
第 3 步:
不要忘记执行此命令:
我已经针对 Rails 4 测试了此解决方案,效果良好。
Three steps to change the type of a column:
Step 1:
Generate a new migration file using this code:
Step 2:
Go to
/db/migrate
folder and edit the migration file you made. There are two different solutions.2.
Step 3:
Don't forget to do this command:
I have tested this solution for Rails 4 and it works well.