在Rails迁移中添加新表格和引用

发布于 2025-01-17 13:13:48 字数 777 浏览 2 评论 0原文

假设我有一个表 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

淡看悲欢离合 2025-01-24 13:13:48

您可以尝试在本地环境上运行迁移和回滚选项。

bin/rails db:migrate
bin/rails db:rollback step=1 # if it is the latest migration

You could try running the migrate and rollback options on your local environment.

bin/rails db:migrate
bin/rails db:rollback step=1 # if it is the latest migration
笨死的猪 2025-01-24 13:13:48

为了测试down方法,您可以获取生产数据库MySQL转储,在本地创建测试数据库并上传脚本,因此您可以使用真实数据测试迁移。

对于组创建,如果您想使用零值创建组实体,则必须将值放入组的创建方法中

Post.all.each { |post| 
      g = Group.create(param1: value1, param2: value2)
      post.group_id = g.id
      post.save
    }

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

Post.all.each { |post| 
      g = Group.create(param1: value1, param2: value2)
      post.group_id = g.id
      post.save
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文