关于rails迁移和同步视图的问题
我是 Rails 初学者,正在尝试了解 Rails 迁移的工作原理。 我创建了一个类似的脚手架:
script/generate scaffold Item col1:string col2:text
rake db:migrate
我想使用迁移添加另一个 col4:
我创建了一个迁移,如下所示:
class AddCol4 < ActiveRecord::Migration
def self.up
add_column :items, :col4, :numeric
Item.reset_column_information
end
def self.down
remove_column :items, :col4
end
end
当我运行 rake db:migrate 时,会添加新列。但是视图不同步。 我应该手动将新列添加到视图中吗?有没有办法使用新的表列自动重新生成模型/视图?
抱歉,这是一个基本问题,但根据我使用其他框架的经验,它应该是自动的。 关于迁移的 Rails 指南并没有明确说明执行迁移后同步应该如何工作。
I am a Rails beginner and trying to understand how rails migration works.
I have created a scaffold like:
script/generate scaffold Item col1:string col2:text
rake db:migrate
I would like to add another col4 using migration:
I created a migration as follows:
class AddCol4 < ActiveRecord::Migration
def self.up
add_column :items, :col4, :numeric
Item.reset_column_information
end
def self.down
remove_column :items, :col4
end
end
When I run rake db:migrate the new column gets added. However the view is out of sync.
Am I supposed to manually add the new column to the view? Is there a way to auto-regenerate the model/view using the new table columns?
Sorry, it is a basic question but from my experience with other frameworks, it should have been automatic.
The rails guide on migration does not make this obvious regarding how the synchronization is supposed to work after you perform a migration.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不幸的是,您需要手动修改视图。该视图是通过运行
script/generatescaffold
命令创建的。迁移仅更改数据库。从技术上讲,您可以重新运行脚手架命令并让它重新生成视图。它会询问您是否要覆盖以前的文件,但是,如果您选择此路线,您仍然需要指定所需的所有列。你不能简单地到处添加一些。如果您处于开发早期,那么您可能会采取这条路线。只需运行
然后重新运行
如果您要创建只有少数用户的东西,可以使用一些动态脚手架扩展,例如 ActiveScaffold将会看到,但我建议您自己编写 HTML,因为它总是会按照您想要的方式显示。
我似乎找不到任何其他动态脚手架插件。曾经有不少...
Unfortunately you will need to modify the view manually. The view is created by running the
script/generate scaffold
command. Migrations only change the database. Technically, you can rerun the scaffold command and have it regenerate the view. It will ask you if you want to overwrite the previous file, however, if you go this route, you will still need to specify ALL of the columns that you want. You can't simply add some here and there.If you are early in development, then you might take this route. Simply run
and then rerun
There are some dynamic scaffolding extensions available such as ActiveScaffold if you are creating something that only a few users will see, but I would recommend doing the HTML yourself as it will always come out the way you want.
I can't seem to find any of the other dynamic scaffolding plugins. There used to be quite a few...