将数据从灯具加载到数据库(关联)



我有两个模型,Project和Todo。

项目存储待办事项数组。

项目迁移:

  def up
    create_table :projects do |t|
      t.string :title, null: false
      t.timestamps null: false
    end
  end

待办事项迁移:

  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

项目.rb

class Project < ActiveRecord::Base
  has_many :todos
end

待办事项.rb

class Todo < ActiveRecord::Base
  belongs_to :project
end

项目.yml

family:
  title: 'Семья'
work:
  title: 'Работа'
therest:
  title: 'Прочее'

待办事项.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 文件(如数组(添加日期?

链接表之间关联的更好方法之一是使用引用。您可以对待办事项表执行此操作

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

这将在您的待办事项表中创建一个名为 project_id 的字段。因此,您有一个包含has_many待办事项的项目表。

可以通过

不同的方式预加载数据库。您可以使用seeds.rb文件,您可以在其中编写代码以从yml文件读取并加载到数据库。你可以做这样的事情

proj = Project.create(title: family)

如果你有一个所有家庭待办事项的数组,那么你可以像这样把它放在数据库中

##Family todos
loop through
  proj.todos << Todo.create(...fields...)
end 
如果要

预填充数据库,那么更好的方法是使用位于db/seeds.rb

只需在这里使用 ruby 和 rails 应用程序中的类,例如,为其创建一个项目和一个待办事项:

project = Project.create!(...)
project.todos.create!(...)

然后只需运行rake db:seed即可执行它。

您可以在此处阅读更多示例:http://www.xyzpub.com/en/ruby-on-rails/3.2/seed_rb.html

最新更新