# Changing database structure without wiping

**URL:** <https://www.ruby-forum.com/t/changing-database-structure-without-wiping/165084>\
**Category:** Rails\
**Created:** [April 8, 2009, 11:45pm UTC](https://www.ruby-forum.com/t/changing-database-structure-without-wiping/165084 "2009-04-08T23:45:47Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![mikec](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/977dab/32.png) [@mikec](https://www.ruby-forum.com/u/mikec)\
**Post date:** [April 8, 2009, 11:45pm UTC](https://www.ruby-forum.com/t/changing-database-structure-without-wiping/165084/1 "2009-04-08T23:45:47Z")

</div>

I’ve decided to make a major change in my application which affects  
more than 1 model. I don’t want to wipe all the data though. Here’s  
the scenario I’m in:

I have a Book model with a Chapter model. Book has many Chapters and  
Chapter belongs to Book. However, I want to add a Story model between  
them so that Book has many Stories and Stories has many Chapters. Is  
there a way I can make this change without wiping all my data?

---

<div class="post-metadata">

**Author:** ![mikec](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/977dab/32.png) [@mikec](https://www.ruby-forum.com/u/mikec)\
**Post date:** [April 9, 2009, 8:42am UTC](https://www.ruby-forum.com/t/changing-database-structure-without-wiping/165084/2 "2009-04-09T08:42:31Z")

</div>

What you’re asking should be totally doable via Migrations. See  
[Active Record Migrations — Ruby on Rails Guides](http://guides.rubyonrails.org/migrations.html).

Basically your flow should look something like:

1. Create stories table.
2. Add column chapters.story\_id.
3. Find all chapters.
4. For each chapter:
  - Find or create the matching story. (Find params will depend on  
structure of story and chapter.)
  - story.book = chapter.book
  - chapter.story = story
  - chapter.book = nil

  1. Remove column chapters.book\_id.

Could also write a one-off script to do this if you’re more comfortable,  
but  
leveraging ActiveRecord in this case will make life easier no matter  
where  
you decide to implement it.

HTH.
