RAILS 5.1
PostgreSQLをデータベースとして使用しているRAILSアプリケーションがあります。RAILSの観点からRAILSデータベースデータをエクスポート/ダンプしたいと思います。だから私はデータベースから独立しています。後で、このエクスポート/ダンプファイルを使用して、データをデータベースにロード/インポート/シードし直したいと思います。
私は次のGEMを試しました:
seed_dump
動作しますが、HABTMモデルの関係を処理できません。
yaml_db、動作しますが、yaml形式はrails db:seedによって理解される形式ではありません
JSONにエクスポートする実際の例を次に示します。私はこの種のことをするためにレーキタスクを使用します。この例では、usersテーブルをダンプしています。
namespace :dataexport do
desc 'export sers who have logged in since 2017-06-30'
task :recent_users => :environment do
puts "Export users who have logged in since 2017-06-30"
# get a file ready, the 'data' directory has already been added in Rails.root
filepath = File.join(Rails.root, 'data', 'recent_users.json')
puts "- exporting users into #{filepath}"
# the key here is to use 'as_json', otherwise you get an ActiveRecord_Relation object, which extends
# array, and works like in an array, but not for exporting
users = User.where('last_login > ?', '2017-06-30').as_json
# The pretty is nice so I can diff exports easily, if that's not important, JSON(users) will do
File.open(filepath, 'w') do |f|
f.write(JSON.pretty_generate(users))
end
puts "- dumped #{users.size} users"
end
end
そしてインポート
namespace :dataimport do
desc 'import users from recent users dump'
task :recent_users => :environment do
puts "Importing current users"
filepath = File.join(Rails.root, 'data', 'recent_users.json')
abort "Input file not found: #{filepath}" unless File.exist?(filepath)
current_users = JSON.parse(File.read(filepath))
current_users.each do |cu|
User.create(cu)
end
puts "- imported #{current_users.size} users"
end
end
インポートプロセスの一部として、クリーンなテーブルをインポートしたい場合があります。その場合、タスクは次のように開始します。
ActiveRecord::Base.connection.execute("TRUNCATE users")
これは、50,000行を超える、またはテキストフィールドが多い、本当に大きなテーブルを処理するための最良の方法ではありません。その場合、dbネイティブダンプ/インポートツールがより適切です。
完全を期すために、HABTMの例を次に示します。リンクテーブルはまだありますが、モデルがないため、それを使用して何かを行う唯一の方法は生のSQLです。たとえば、ユーザーに多くの役割があり、その逆(ユーザーのM:M役割)があると想像してみましょう。
class User < ApplicationRecord
has_and_belongs_to_many :roles
end
class Role < ApplicationRecord
has_and_belongs_to_many :users
end
必ずしもそこと呼ばれる参加テーブルだろうusers_roles
2つの列を持っていることになる、user_id
とrole_id
。HABTMのRailsガイドを参照してください
エクスポートするには、SQLを直接実行する必要があります。
users_roles = ActiveRecord::Base.connection.execute("SELECT * from users_roles").as_json
# and write the file as before
SQLを実行してインポートします
# read the file, same as before
user_roles.each do |ur|
ActiveRecord::Base.connection.execute("insert into users_roles (user_id, role_id) values ('#{ur[0]}', '#{ur[1]}')")
end
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加