Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate table on migration down method of ActiveRecord Rails 3.1

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 ?

like image 548
Mr_Nizzle Avatar asked Nov 15 '11 15:11

Mr_Nizzle


People also ask

How do you destroy migration in Rails?

【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!

How do I rollback a specific migration in Rails?

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.


2 Answers

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!

like image 114
Abhishek Avatar answered Nov 16 '22 03:11

Abhishek


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
like image 22
Trung Lê Avatar answered Nov 16 '22 02:11

Trung Lê