2

My app is in beta, and I've been doing limited testing of a feature that involves a new model. After a fair amount of testing I had to make a structural change that makes the old data non-functional.

What I need to do is just drop and recreate one table. I know that I could do this in a migration, but that seems like such a hack. In a local dev copy I would just use db:reset, but in the beta app I don't want to lose data in any tables except this one.

Is this a simple way to instruct a production app to drop and recreate a single table. In my case, I'm deploying with Heroku, in case that affects how you would solve this issue.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Andrew
  • 42,517
  • 51
  • 181
  • 281

4 Answers4

8

To empty a table on Heroku without changing the schema, in your application's directory:

$ heroku run console
Ruby console for myap.heroku.com
>> ModelName.delete_all
>> exit
lflores
  • 3,770
  • 3
  • 19
  • 24
ghoppe
  • 21,452
  • 3
  • 30
  • 21
  • Thanks, this works perfectly and seems more straightforward than a drop/recreate migration. Out of curiosity, would this also reset the IDs auto-increment back to 1? That's not essential, but it would feel cleaner to me if the first record (post erase) still started at ID:1 – Andrew Mar 09 '11 at 04:23
  • 1
    @Andrew I believe truncate is the sql command you're looking for. Docs at http://www.postgresql.org/docs/9.1/static/sql-truncate.html – Ameen Nov 25 '13 at 05:20
  • On heroku, you now use "heroku run rails console" – Jeff Ancel Apr 24 '14 at 22:21
1

I know that I could do this in a migration, but that seems like such a hack.

It's not a hack. It's precisely what migrations are designed to do.

jdl
  • 17,702
  • 4
  • 51
  • 54
  • Even when you're making no change to the schema, just "recreating" a table? – Andrew Mar 07 '11 at 20:18
  • 1
    @Andrew I thought you said you made structural changes that makes the old data non-functional? So the schema would be different, right? – ghoppe Mar 07 '11 at 20:36
  • I guess what I mean is, the schema evolved over several migrations in such a way that the old data is no longer fully functional. The schema NOW is correct, but some of the associations etc. have changed enough that the old data sometimes raises exceptions. – Andrew Mar 07 '11 at 23:25
0
heroku run console
irb(main):001:0> ModelName.delete_all

And you are done.

Saqib R.
  • 2,919
  • 2
  • 26
  • 21
0

You need to rerun the migration for that table to make structural changes. I haven't used ActiveRecord before, but I'd also delete the data in the table using ModelName.delete_all from heroku console.

picardo
  • 24,530
  • 33
  • 104
  • 151