我怎么可以加载一些ActiveRecord模型从YAML文件并将其保存到数据库?模型、加载、数据库、我怎么

2023-09-09 22:04:34 作者:酷到招风

我想节省一些查表数据输出到一个YAML文件,以便后来当我需要设置我的应用程序在不同的机器上,我可以加载数据作为种子数据。

I'm trying to save some lookup table data out to a YAML file so that later when I need to set up my app on a different machine I can load the data in as seed data.

中的数据是这样的东西选择选项,这是pretty的多集,所以不愁实时数据序列化和反序列化之间变化。

The data is stuff like select options, and it's pretty much set, so no worries about the live data changing between serializing and deserializing.

我有这样的输出数据...

I have output the data like this...

file = File.open("#{RAILS_ROOT}/lib/tasks/questions/questions.yml", 'w')
questions = Question.find(:all, :order => 'order_position')
file << YAML::dump(questions)
file.close()

和我可以加载这样的文件...

And I can load the file like this...

questions = YAML.load_file('lib/tasks/questions/questions.yml')

然而,当我尝试保存问题,我得到这个错误...

However, when I try to save a question I get this error...

>> questions[0].save
NoMethodError: undefined method `save' for #<YAML::Object:0x2226b84>

什么是做这种正确的方法是什么?

What is the correct way to do this?

推荐答案

我想你的情况下,我没有任何问题。我做了以下更改YAML文件的创建逻辑:

I tried your scenario and I did not have any issues. I did the following changes to your YAML file creation logic:

yml_file = Rails.root.join('lib', 'tasks', 'questions', 'questions.yml')
File.open(yml_file, 'w') do |file|
  questions = Question.order(:order_position).to_a
  YAML::dump(questions, file)
end

我能够检索问题名单如下:

yml_file = Rails.root.join('lib', 'tasks', 'questions', 'questions.yml')
questions = YAML.load_file(yml_file).map{|q| Question.create(q.attributes)}