I need to change a reference for a model while updating the value and not allowing this reference to have null values.
I would like to reference Animal
to Specie
instead of Breed
.
I will not remove Breed
from this migration so I can keep it until I make sure everything works properly in production and then will run a cleanup.
Here we go:
class AddSpeciesToAnimal < ActiveRecord::Migration[5.2]
def down
remove_reference :animals, :specie, foreign_key: true, index: true
end
def up
add_reference :animals, :specie, foreign_key: true, index: true
Animal.find_each { |animal| animal.update!(specie: animal.breed.specie) }
change_column_null :animals, :specie_id, false
end
end