如何从 YAML 文件加载一些 ActiveRecord 模型并将它们保存到数据库?

发布于 2024-08-22 20:31:07 字数 654 浏览 4 评论 0原文

我正在尝试将一些查找表数据保存到 YAML 文件中,以便稍后当我需要在另一台计算机上设置我的应用程序时,我可以将数据作为种子数据加载。

数据类似于选择选项,而且已经基本设置完毕,因此不必担心实时数据在序列化和反序列化之间发生变化。

我已经输出这样的数据...

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

并且我可以像这样加载文件...

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

但是,当我尝试保存问题时,我收到此错误...

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

正确的方法是什么?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

心凉 2024-08-29 20:31:07

db 目录中创建一个 seed.yml 文件。为您要创建的每个模型添加一个 YAML 文档。该文件应包含哈希列表。每个哈希应该包含模型属性。

  users:
      -   login: jake
          password: jake123
          password_confirmation: jake123
          first_name: Jake
          last_name: Driver

      -   login: Jane
          password: jane123
          password_confirmation: jane123
          first_name: Jane
          last_name: McCain

  categories:

  products:

在您的seed.rb文件中

seed_file = File.join(Rails.root, 'db', 'seed.yml')
config = YAML::load_file(seed_file)
User.create(config["users"])
Category.create(config["categories"])
Product.create(config["products"])

运行rake任务来加载行

rake db:seed

Create a seed.yml file in db directory. Add a YAML document for each model you want to create. This document should contain a list of hash. Each hash should contain model attributes.

  users:
      -   login: jake
          password: jake123
          password_confirmation: jake123
          first_name: Jake
          last_name: Driver

      -   login: Jane
          password: jane123
          password_confirmation: jane123
          first_name: Jane
          last_name: McCain

  categories:

  products:

In your seed.rb file

seed_file = File.join(Rails.root, 'db', 'seed.yml')
config = YAML::load_file(seed_file)
User.create(config["users"])
Category.create(config["categories"])
Product.create(config["products"])

Run the rake task to load the rows

rake db:seed
相思碎 2024-08-29 20:31:07

接受的答案实际上回答了问题吗?看起来提问者想要保存模型,而不仅仅是从 YAML 文件中检索它们。

要真正将加载的模型保存回数据库,您需要欺骗ActiveRecord,使其认为模型需要保存。你可以用这段相当脏的代码来做到这一点,

questions = YAML.load_file("#{RAILS_ROOT}/lib/tasks/questions/questions.yml")
questions.each{|q| q.instance_variable_set("@new_record", true); q.save}

它可以工作,并保存了我的培根一两次。

Does the accepted answer actually answer the question? It looks like the asker wanted to save the models, not just retrieve them from a YAML file.

To actually save the loaded model(s) back to the database you need to fool ActiveRecord into thinking the model needs saving. You can do it with this rather dirty bit of code

questions = YAML.load_file("#{RAILS_ROOT}/lib/tasks/questions/questions.yml")
questions.each{|q| q.instance_variable_set("@new_record", true); q.save}

It works and saved my bacon once or twice.

挽袖吟 2024-08-29 20:31:07

我尝试了你的场景,没有任何问题。我对 YAML 文件创建逻辑进行了以下更改:

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 列表,如下所示:

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)

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

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)
—━☆沉默づ 2024-08-29 20:31:07

如果您使用的是 Rails 2.3.4(或更高版本),它们有一个 seeds.rb 文件,可以在您的应用程序 db 文件夹中找到。这使您可以定义基本的活动记录创建,当您设置新项目时,您可以简单地调用:

rake db:seed

有一个很棒的 Railscast 位于此处,以及关于它的好博文这里。如果您没有使用 Rails 2.3.4(或者,理想情况下是 2.3.5),我强烈建议您更新这些很酷的功能,并进行额外的安全/错误修复。

If you're using Rails 2.3.4 (or above), they have a seeds.rb file that can be found in your applications db folder. This lets you define basic active record creates, and when you've set up your new project, you can simply call:

rake db:seed

There is an excellent Railscast on it here, and a good blog post about it here. If you're not using Rails 2.3.4 (Or, ideally, 2.3.5), I highly recommend updating for these cool features, and addition security/bug fixes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文