这是一个导出为 JSON 的实际示例。我使用 rake 任务来做这种事情。在此示例中,我正在转储用户表。
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 行和/或包含大量文本字段。在这种情况下,数据库原生转储/导入工具会更合适。
为了完整起见,这里是一个 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 的连接表,它有两列,user_id 和role_id。
See the Rails Guide on HABTM
要导出,我们必须直接执行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
See this answer for more on inserting with raw SQL