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

Eth*_*han 12 ruby activerecord yaml ruby-on-rails

我正在尝试将一些查找表数据保存到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()
Run Code Online (Sandbox Code Playgroud)

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

questions = YAML.load_file('lib/tasks/questions/questions.yml')
Run Code Online (Sandbox Code Playgroud)

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

>> questions[0].save
NoMethodError: undefined method `save' for #<YAML::Object:0x2226b84>
Run Code Online (Sandbox Code Playgroud)

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

Har*_*tty 21

seed.ymldb目录中创建一个文件.为要创建的每个模型添加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:
Run Code Online (Sandbox Code Playgroud)

在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"])
Run Code Online (Sandbox Code Playgroud)

运行rake任务以加载行

rake db:seed
Run Code Online (Sandbox Code Playgroud)


Ben*_*Ben 11

接受的答案是否真的回答了这个问题?看起来问问者想要保存模型,而不仅仅是从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}
Run Code Online (Sandbox Code Playgroud)

它起作用并保存了我的培根一两次.


Har*_*tty 10

我尝试了你的场景,我没有任何问题.我对您的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
Run Code Online (Sandbox Code Playgroud)

我能够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)
Run Code Online (Sandbox Code Playgroud)