2

I'd like to be able to:

  1. Clear out one table, including resetting the primary key(s)
  2. Use db:seed to refill that table with new data
  3. Keep all other tables the same, with data intact

I understand this is possible by having a migration that drops the table and recreates it on rollback (like this blog post); however, that could be annoying to keep updated if I change the table schema in a later migration.

Is there a better way than the solution above to achieve the 3 effects I'm looking for, ideally one that dynamically adapts to the existing structure of the dropped table, either directly or through the collective impact of all applicable migrations? Thanks!


Edit: two things that may help other new people when using the answer below:

  • In create_fixtures, my first argument ended up as "#{Rails.root}/test/fixtures" - I didn't know before hand about Rails.root
  • For how to do basic custom rake tasks, there's a Railscast.
Matthew Du Pont
  • 187
  • 1
  • 1
  • 13

1 Answers1

1

You're on the right track on thinking of using the rake db:seed task:

Using fixtures to fill a table clears that table and resets the id's. So, to meet your first requirement, create a rake task that loads your fixture file that is created exclusively for your special table. I recommend using a separate rake task from rake db:seed as it leaves you free to use that task as normal, and it's not hard to type rake db:seed && rake db:special_table_seed.

Create a separate yml file my_table.yml with your table seed data

The commands you want to use in the rake task is

require 'active_record/fixtures'

ActiveRecord::Fixtures.create_fixtures("/path/to/the/directory/", "my_table")

As for your final need of the process dynamically adapting to changes in the table structure, I don't have any suggestions - sorry. One way to try to do this IS to use a migration to manage it BUT that is generally looked at as very hard to maintain, and I don't recommend it. You're better off doing the work of assessing the change that needs to be done to the seed file with each significant change to your structure.

Tonys
  • 3,349
  • 4
  • 24
  • 27