How to load data from a .yml file into a database?

There is a questions table and a questions.yml data file. Suppose there is no Question model.

'questions.yml' has some recodes dump from the table.

 --- questions_001: title: ttt1 content: ccc1 questions_002: title: ttt2 content: ccc2 

I want to load data from a yml file, paste it into the database. But I can’t use rake db:fixtures:load , because it will treat the content as an β€œerb” template that it doesn’t want, I want

So, I want to write another rake task to manually load the data.

I can read the entries:

 File.open("#{RAILS_ROOT}/db/fixtures/#{table_name}.yml", 'r') do |file| YAML::load(file).each do |record| # how to insert the record?? end end 

But I do not know how to insert them.


Edit:

I tried:

 Class.new(ActiveRecord::Base).create(record) 

and

 class Dummy < ActiveRecord::Base {} Dummy.create(rcord) 

But nothing has been added to the database.

+4
source share
3 answers

Try this after loading the date from the yml file into records :

 class Question < ActiveRecord::Base # Question model just to import the yml file end records.each { |record| Question.create(record) } 

You can simply create a model for import only. You do not need to create app/models/question.rb . Just write the code in the import script.

UPDATE:

You can use the following function:

 def create_class(class_name, superclass, &block) klass = Class.new superclass, &block Object.const_set class_name, klass end 

a source

 File.open("#{RAILS_ROOT}/db/fixtures/#{table_name}.yml", 'r') do |file| YAML::load(file).each do |record| model_name = table_name.singularize.camelize create_class(model_name, ActiveRecod::Base) do set_table_name table_name.to_sym end Kernel.const_get(model_name).create(record) end end 

To use the connection directly, you can use the following:

 ActiveRecord::Base.connection.execute("YOUR SQL CODE") 
+7
source

This loads the fixtures into the current RAILS_ENV, which is a development by default.

 $ rake db:fixtures:load 
+1
source

Got the job thanks to @ jigfox's answer. I had to modify the bit for full implementation now with Rails 4.

 table_names = Dir.glob(Rails.root + 'app/models/**.rb').map { |s| Pathname.new(s).basename.to_s.gsub(/\.rb$/,'') } table_names.each do |table_name| table_name = table_name.pluralize path = "#{Rails.root}/db/fixtures/#{table_name}.yml" if File.exists?(path) File.open(path, 'r') do |file| y = YAML::load(file) if !y.nil? and y y.each do |record| model_name = table_name.singularize.camelize rec = record[1] rec.tap { |hs| hs.delete("id") } Kernel.const_get(model_name).create(rec) end end end end end 
0
source

Source: https://habr.com/ru/post/1313356/


All Articles