Ruby on rails 将数据从装置加载到数据库(关联)
我有两个模型,Project和Todo 项目存储TODO数组 项目迁移:Ruby on rails 将数据从装置加载到数据库(关联),ruby-on-rails,ruby,database,yaml,fixtures,Ruby On Rails,Ruby,Database,Yaml,Fixtures,我有两个模型,Project和Todo 项目存储TODO数组 项目迁移: def up create_table :projects do |t| t.string :title, null: false t.timestamps null: false end end Todo的迁移: def up create_table :todos do |t| t.string :text, null: false
def up
create_table :projects do |t|
t.string :title, null: false
t.timestamps null: false
end
end
Todo的迁移:
def up
create_table :todos do |t|
t.string :text, null: false
t.boolean :isCompleted, null:false
t.integer :project_id, null:false
t.timestamps null: false
end
end
project.rb
class Project < ActiveRecord::Base
has_many :todos
end
todos.yml
family_todos:
text: 'Купить молоко'
isCompleted: false
project_id: family
work_todos:
text: 'Закончить проект'
isCompleted: false
project_id: work
therest_todos:
text: 'Познать бесконечность'
isCompleted: true
project_id: therest
如何正确地连接它们,以便在调用项目时可以看到其中的所有待办事项?另外,我很好奇如何通过像数组一样的yml文件添加日期?如果您想预填充数据库,那么更好的方法是使用
seeds.rb
,它位于db/
中
只需在此处使用ruby和rails应用程序中的类,例如,为其创建项目和todo:
project = Project.create!(...)
project.todos.create!(...)
然后只需运行rakedb:seed
即可执行它
您可以通过这里的示例阅读更多内容:链接表之间关联的更好方法之一是使用引用。您可以对todos表执行此操作
def up
create_table :todos do |t|
t.string :text, null: false
t.boolean :isCompleted, null:false
t.references :project, references: :projects, index: true, foreign_key: true
t.timestamps null: false
end
end
这将在todos表中创建一个名为project_id的字段。因此,您有一个项目表,其中有许多待办事项
有不同的方法可以预加载数据库。您可以使用seeds.rb文件,在这里您可以编写代码从yml文件读取并加载到数据库。
你可以这样做
proj = Project.create(title: family)
##Family todos
loop through
proj.todos << Todo.create(...fields...)
end
若您有一个包含所有家庭待办事项的数组,那个么您可以像这样将其放入数据库中
proj = Project.create(title: family)
##Family todos
loop through
proj.todos << Todo.create(...fields...)
end
家庭待办事项
循环通过
你能回答我吗?我怎样才能得到所有的待办事项?例如,我需要打印家庭项目中的所有待办事项。你能行