Truncate a table by migrating down ActiveRecord Rails 3.1

I have the following definition in my up method during my migration to set the source 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 that I can apply to the down method, for example:

 def down Color.truncate end 

Or, since I set the identifiers to create, should I only use the destroy_all method of the Color model?

+4
source share
2 answers

You can simply use this in your up method, it will also solve your problem with truncating and resetting identifiers.

 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 

Hooray!

+7
source

First, you do not need to pass :id to create! , because ActiveRecord automatically handles this, thus :id can be ignored (standard case is assumed).

Secondly, it is not recommended to use the ActiveRecord query constructor during migration, because if the color name of the model is changed, you must have a broken migration. I highly recommend you use pure SQL and execute this query with execute() .

Third, for the #down method #down you should not truncate the table. You must destroy the 4 colors that you created in #up .

Here is how I wrote it:

 def down colors = ["FF6633", "93B233", "4D90D9", "C43092"] Color.where(:color => colors).destroy_all end 
0
source

Source: https://habr.com/ru/post/1381325/


All Articles