I have the following defined on my up
method on my migration to set initial data:
def up
Color.create!({:id=>1,:name=>"",:color=>"FF6633"})
Color.create!({:id=>2,:name=>"",:color=>"93B233"})
Color.create!({:id=>3,:name=>"",:color=>"4D90D9"})
Color.create!({:id=>4,:name=>"",:color=>"C43092"})
end
Is there any truncate
directive I can put on the down
method like:
def down
Color.truncate
end
Or since I'm setting the IDs on the create should I use only the destroy_all
method of the model Color
?
【Ruby on Rails】 When you want to delete a migration file you made, you can choose version and delete it. You don't need to execute rails db:rollback many times!
To check for status, run rails db:migrate:status . Then you'll have a good view of the migrations you want to remove. Then, run rails db:rollback to revert the changes one by one. After doing so, you can check the status again to be fully confident.
You can simple use this in your up
method, this will solve your both truncate and id resetting problem also.
def up
ActiveRecord::Base.connection.execute("TRUNCATE table_name")
Color.create!({:id=>1,:name=>"",:color=>"FF6633"})
Color.create!({:id=>2,:name=>"",:color=>"93B233"})
Color.create!({:id=>3,:name=>"",:color=>"4D90D9"})
Color.create!({:id=>4,:name=>"",:color=>"C43092"})
end
Cheers!
Firstly, you don't have to pass :id
into create!
because ActiveRecord will automatically handle that, thus :id
likely to get ignored (standard case assumed).
Secondly, it is not a good practice to use ActiveRecord query builder in migration because should the model Color name be changed, you are to have a broken migration. I highly recommend you to use pure SQL and execute that query with execute()
.
Thirdly, for the #down
method, you shouldn't truncate the table. You should destroy those 4 colors that you created in #up
.
Here's how I would write it:
def down
colors = ["FF6633", "93B233", "4D90D9", "C43092"]
Color.where(:color => colors).destroy_all
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With