Home > Mobile >  Add new table and references to it in rails migration
Add new table and references to it in rails migration

Time:04-04

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?

CodePudding user response:

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

CodePudding user response:

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
    }
  • Related