如何从 YAML 文件加载一些 ActiveRecord 模型并将它们保存到数据库? [英] How can I load some ActiveRecord models from a YAML file and save them to the DB?

查看:14
本文介绍了如何从 YAML 文件加载一些 ActiveRecord 模型并将它们保存到数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一些查找表数据保存到 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.

数据就像选择选项一样,而且几乎已经设置好了,所以不用担心实时数据在序列化和反序列化之间发生变化.

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

我能够检索到 questions 列表如下:

I was able to retrieve the questions list as follows:

yml_file = Rails.root.join('lib', 'tasks', 'questions', 'questions.yml')
question_attributes_list = YAML.load_file(yml_file).map(&:attributes)
questions = Question.create(question_attributes_list)

这篇关于如何从 YAML 文件加载一些 ActiveRecord 模型并将它们保存到数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆