在Rails迁移中添加新表格和引用
假设我有一个表 posts
,我想将它们分组在一起。为此,我想创建一个新表groups
,其中posts
具有到groups
的fk。生产数据库已经填充了许多帖子,并且每个帖子一开始就应该属于自己的组(帖子 1 属于组 1,应该创建该组,帖子 2 应该属于组 2,该组应该创建等)
到目前为止,我已经提出了这个解决方案,但我不确定这是否是实现此目的的最佳方法:
class AddGroups < ActiveRecord::Migration[7.0]
def up
create_table :groups do |t|
t.timestamps
end
add_reference :posts, :group, index: true
Post.all.each { |post|
g = Group.create
post.group_id = g.id
post.save
}
change_column_null :posts, :group_id, false
end
def down
remove_reference :posts, :group, index: true, null: false
drop_table :groups
end
end
此外,如何测试 down
方法是否是正确的?
Say I have a table posts
, and I want to group them together. For this I want to create a new table groups
, with posts
having a fk to groups
. The production db is already populated with many posts
and each post should belong to its own group to begin with (post 1 belongs to group 1, which should be created, post 2 should belong to group 2, which should be created, etc)
So far I've come up with this solution, but I'm not sure if it's the best way to achieve this:
class AddGroups < ActiveRecord::Migration[7.0]
def up
create_table :groups do |t|
t.timestamps
end
add_reference :posts, :group, index: true
Post.all.each { |post|
g = Group.create
post.group_id = g.id
post.save
}
change_column_null :posts, :group_id, false
end
def down
remove_reference :posts, :group, index: true, null: false
drop_table :groups
end
end
Moreover, how do I test if the down
method is correct?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以尝试在本地环境上运行迁移和回滚选项。
You could try running the migrate and rollback options on your local environment.
为了测试
down
方法,您可以获取生产数据库MySQL转储,在本地创建测试数据库并上传脚本,因此您可以使用真实数据测试迁移。对于组创建,如果您想使用零值创建组实体,则必须将值放入组的创建方法中
For test the
down
method you can get a production database mysql dump, create a test db locally and upload the script, so you can test the migration with real data.For the groups creation, if you want create Group entity with null values is ok, otherwise you must put the value inside the group's create method