Sve*_*ten 5 ruby-on-rails ruby-on-rails-5
导轨 5.1
我有一个使用 PostgreSQL 作为数据库的 RAILS 应用程序。我想从 RAILS 的角度导出/转储 RAILS 数据库数据。所以我独立于数据库。后来我想使用这个导出/转储文件将数据加载/导入/播种回数据库。
我尝试了以下 GEM:
seed_dump
可以用,但是不能处理HABTM 模型关系。
yaml_db,它有效,但 yaml 格式不是rails db:seed理解的格式
这是导出为 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
Run Code Online (Sandbox Code Playgroud)
然后导入
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
Run Code Online (Sandbox Code Playgroud)
有时作为导入过程的一部分,我希望导入一个干净的表,在这种情况下,我会使用以下命令启动 taske:
ActiveRecord::Base.connection.execute("TRUNCATE users")
Run Code Online (Sandbox Code Playgroud)
这不是处理真正大表的最佳方式,大于,哦,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
Run Code Online (Sandbox Code Playgroud)
必然会有一个名为的连接表users_roles,它有两列,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
Run Code Online (Sandbox Code Playgroud)
并执行 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8680 次 |
| 最近记录: |