简体   繁体   中英

Best way to add Data to rails app after db has been seeded

I am working on a rails app, I need to add data to the database through a csv. I am not able to do this through my seed file because I already have users and the seed file is not set up to be run more than once. I am planning on doing this through a migration where I load in the csv in and parse it, creating the objects. I am not sure if this is best practice and would like do this the correct way, or is there a better way to do this?

The Rails migration files should be reserved for database manipulation (add/remove/change tables/columns). Ie avoid populating data with them. Mainly because if you are attempting to populate data and something goes wrong then your whole deploy will fail. But also because it's only useful when running the migration (so future developers will not benefit when simply loading schema later).

The pattern I've fallen back on over the years is to write a Rake task to handle data migrations that I can call after doing the server deploy. For more on how to create a rake task, refer to this Rails Guide on the subject. Basically, just define a new Rake task namespaced to your app and then use standard Ruby code to run through records and add/change/remove data as needed. Here's a simple example:

# lib/tasks/release.rake

namespace :release do
  task cache_game_winners: :environment do
    puts "=" * 80
    Game.completed.each do |game|
      next if game.tied? || game.winner_id?
      game.winner = if game.home_player_score > game.away_player_score
                      game.home_player
                    else
                      game.away_player
                    end
      puts "Updating #{game.identify(:id, :home_player_id, :home_player_score, :away_player_id, :away_player_score)}: #{game.changes}"
      game.save(validate: false)
    end
    puts "== Done #{"=" * 72}"
  end
end

Note: the call to identify in the puts statement comes from the object_identifier gem .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM