Ruby on Rails - adding a not null constraint in existing data in ruby on rails- ruby on rails tutorial - rails guides - rails tutorial - ruby rails
- We want to add a foreign key company_id to the users table.
- We want to have a NOT NULL constraint on it.
- If we already have data in users, we will have to do this in multiple steps.
class AddCompanyIdToUsers < ActiveRecord::Migration
def up
# add the column with NULL allowed
add_column :users, :company_id, :integer
# make sure every row has a value
User.find_each do |user|
# find the appropriate company record for the user
# according to your business logic
company = Company.first
user.update!(company_id: company.id)
end
# add NOT NULL constraint
change_column_null :users, :company_id, false
end
# Migrations that manipulate data must use up/down instead of change
def down
remove_column :users, :company_id
end
end