@@ -724,17 +724,16 @@ class ExampleMigration < ActiveRecord::Migration[7.1]
724
724
725
725
reversible do |direction |
726
726
direction.up do
727
- # add a CHECK constraint
727
+ # create a distributors view
728
728
execute <<-SQL
729
- ALTER TABLE distributors
730
- ADD CONSTRAINT zipchk
731
- CHECK (char_length(zipcode) = 5 ) NO INHERIT ;
729
+ CREATE VIEW distributors_view AS
730
+ SELECT id, zipcode
731
+ FROM distributors ;
732
732
SQL
733
733
end
734
734
direction.down do
735
735
execute <<-SQL
736
- ALTER TABLE distributors
737
- DROP CONSTRAINT zipchk
736
+ DROP VIEW distributors_view;
738
737
SQL
739
738
end
740
739
end
@@ -774,11 +773,11 @@ class ExampleMigration < ActiveRecord::Migration[7.1]
774
773
t.string :zipcode
775
774
end
776
775
777
- # add a CHECK constraint
776
+ # create a distributors view
778
777
execute <<-SQL
779
- ALTER TABLE distributors
780
- ADD CONSTRAINT zipchk
781
- CHECK (char_length(zipcode) = 5 ) ;
778
+ CREATE VIEW distributors_view AS
779
+ SELECT id, zipcode
780
+ FROM distributors ;
782
781
SQL
783
782
784
783
add_column :users , :home_page_url , :string
@@ -790,8 +789,7 @@ class ExampleMigration < ActiveRecord::Migration[7.1]
790
789
remove_column :users , :home_page_url
791
790
792
791
execute <<-SQL
793
- ALTER TABLE distributors
794
- DROP CONSTRAINT zipchk
792
+ DROP VIEW distributors_view;
795
793
SQL
796
794
797
795
drop_table :distributors
@@ -832,27 +830,25 @@ The `revert` method also accepts a block of instructions to reverse. This could
832
830
be useful to revert selected parts of previous migrations.
833
831
834
832
For example, let's imagine that ` ExampleMigration ` is committed and it is later
835
- decided it would be best to use Active Record validations, in place of the
836
- ` CHECK ` constraint, to verify the zipcode.
833
+ decided that a Distributors view is no longer needed.
837
834
838
835
``` ruby
839
- class DontUseConstraintForZipcodeValidationMigration < ActiveRecord ::Migration [7.1 ]
836
+ class DontUseDistributorsViewMigration < ActiveRecord ::Migration [7.1 ]
840
837
def change
841
838
revert do
842
839
# copy-pasted code from ExampleMigration
843
840
reversible do |direction |
844
841
direction.up do
845
- # add a CHECK constraint
842
+ # create a distributors view
846
843
execute <<-SQL
847
- ALTER TABLE distributors
848
- ADD CONSTRAINT zipchk
849
- CHECK (char_length(zipcode) = 5 ) ;
844
+ CREATE VIEW distributors_view AS
845
+ SELECT id, zipcode
846
+ FROM distributors ;
850
847
SQL
851
848
end
852
849
direction.down do
853
850
execute <<-SQL
854
- ALTER TABLE distributors
855
- DROP CONSTRAINT zipchk
851
+ DROP VIEW distributors_view;
856
852
SQL
857
853
end
858
854
end
0 commit comments