我在Rails中很陌生,但是遇到了问题。像这样从YML文件加载数据的最佳方法是什么:
projects:
- title: 'family'
todos:
- text: 'Get some milk'
isCompleted: false
- text: 'Cook some bacon'
isCompleted: true
- text: 'Repair the front door'
isCompleted: false
- title: 'work'
todos:
- text: 'Call my boss'
isCompleted: true
- text: 'Finish my work tasks'
isCompleted: true
- text: 'Get fired'
isCompleted: false
- title: 'therest'
todos:
- text: 'Do something'
isCompleted: false
- text: 'Ask a question on stackoverflow'
isCompleted: false
因此,我有两个模型-待办事项模型(文本和isCompleted字段)和项目模型(仅标题字段)。项目has_many待办事项。 我试图这样做:
seed_file = Rails.root.join('db', 'seeds', 'seeds.yml')
config = YAML::load_file(seed_file)
Project.create!(config)
但是我有一个错误:
ActiveModel::UnknownAttributeError: unknown attribute 'projects' for Project.
我该如何解决?
答案 0 :(得分:2)
class Project < ApplicationRecord
has_many :todos
accepts_nested_attributes_for :todos
end
Project.create!(title: 'family',
todos_attributes:[{text:'1',isCompleted:false},
{text:'2',isCompleted:false},...])
如果必须使用YAML,则必须阅读YAML,然后将其转换为Rails可以用来创建实体的东西。将其放在您的种子文件中:
yaml_hash = YAML.load(File.read('db/your_yaml.yaml'))
rails_arr_of_hashes = yaml_hash['projects'].map{|p| {title: p['title'], todos_attributes: p['todos'] }
Project.create(rails_arr_of_hashes)
将您的YAML放入db / your_yaml.yaml,然后运行
rails db:seed
请记住将accepts_nested_attributes_for :todos
添加到Project模型中。
祝您学习Rails好运:)
答案 1 :(得分:2)
如聊天中所讨论的,您将需要使用以下内容:
config[:projects].each do |project|
todos = project[:todos]
project.delete(:todos)
new_project = Project.create(project)
todos.each do |todo|
new_project.todos.create(todo)
end
end
假定您的YML格式正确。