dagda1
dagda1

Reputation: 28860

Insert data in migration if it does not exist

I have the following migration:

Sequel.migration do
  up do
    create_table :user_settings do
      primary_key :id

      String :signature, null: true, text: true
    end

    alter_table :user_settings do
      add_foreign_key :user_id, :users, null: false, on_delete: :cascade

      add_index :user_id
    end
  end

  down do
    drop_table :user_settings
  end
end

This will add default user settings.

The problem I have is that I want to create a row in the user_settings table for every user who is currently in the database that does not have a row, prior to this migration.

I want to check if each user has a row with a a matching user_id in the database and if not, I want to insert some default values.

How can I do this in a migration?

Upvotes: 1

Views: 542

Answers (2)

dagda1
dagda1

Reputation: 28860

I ended up with this:

Sequel.migration do
  up do
    existing_settings = SequelAdapter::UserSettings.select(:user_id).to_a

    SequelAdapter::User.exclude(id: existing_settings).each do |user|
      SequelAdapter::UserSettings.create({user_id:  user.id})
    end
  end
end

Thanks @bachan Smruty who pointed me in the right direction but there is no includes method.

Upvotes: 1

Bachan Smruty
Bachan Smruty

Reputation: 5734

Normally, this kind of things are done using rake task but you need in the migration. I guess you have added the association in the User and UserSetting model and it will be has_one association. You need to create a new migration file

def up
  users = User.includes([:user_setting]).where(:user_setting => {:user_id => nil})
  users.each do |user|
    user.create_user_setting
    # OR you can write
    # UserSetting.create({:user_id => user.id, :signature => 'your-custom-text'})
  end
end

Upvotes: 2

Related Questions