ruby 从当前环境的数据库中转储装置
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 从当前环境的数据库中转储装置相关的知识,希望对你有一定的参考价值。
# Source: http://blog.ivanilves.com/2016/rails-dump-fixtures-from-db/
# Usage:
# * rake db:fixtures:dump to dump all models.
# * rake db:fixtures:dump MODELS="user billing_account" to dump only User and BillingAccount models.
# * rake db:fixtures:dump EXCEPT="user billing_account" to dump all, except for User and BillingAccount models.
#
namespace :db do
namespace :fixtures do
def all_models
# HT: mustafa http://blog.ivanilves.com/2016/rails-dump-fixtures-from-db/#comment-6562
if Rails::VERSION::STRING.split('.')[0].to_i <= 4
ActiveRecord::Base.subclasses
else
ApplicationRecord.subclasses
end
end
def selected_models
return nil unless ENV['MODELS']
selected_model_names = ENV['MODELS'].split(/\s+|,/).map(&:camelcase)
all_models.select { |m| selected_model_names.include?(m.name) }
end
def excluded_models
return nil unless ENV['EXCEPT']
excluded_model_names = ENV['EXCEPT'].split(/\s+|,/).map(&:camelcase)
all_models.reject { |m| excluded_model_names.include?(m.name) }
end
desc "Dump fixtures from the current environment's database"
task dump: :environment do
Rails.application.eager_load!
models = excluded_models || selected_models || all_models
models.each do |model|
file_name = "#{Rails.root}/test/fixtures/#{model.name.underscore.pluralize}.yml"
puts "Dumping: #{model.name} => #{file_name}"
File.open(file_name, 'w') do |file|
data = {}
model.all.map(&:attributes).each do |record|
data["#{model.name.underscore}_#{record['id'].to_s}"] = record
end
file.write data.to_yaml
end
end
end
end
end
以上是关于ruby 从当前环境的数据库中转储装置的主要内容,如果未能解决你的问题,请参考以下文章