创建一个新表与一个一对多的关系

问题描述 投票:-1回答:2

我使用Rails 2的旧钢轨项目。已经有模型类Student。在数据库中,有一个表students。现在,我需要实现每个学生可以有多种课程。我需要这意味着要在数据库中的新表的courses表及有从学生到课程一个一对多的关系。

如何创建迁移文件,使这个?

ruby-on-rails ruby-on-rails-2
2个回答
0
投票

梁2并没有一个选项,通过迁移发生器创建关联,所以你必须采取更手动方法。

您可以创建正是如此迁移:https://www.tutorialspoint.com/ruby-on-rails-2.1/rails-migrations.htm

你需要列student_id与列类型courses添加到您的integer

那么下面添加到您的Student型号:

has_many :courses


0
投票

如果你实际上是使用Rails 2.3这应该不会太困难

和TBH如果你是不是至少在2.3,那么你或许应该只是重新创建这个项目完全是...

1)使用ruby script/generate model Course name:string description:text student_id:bigint产生迁移,这应该是这个样子:

class CreateCourses < ActiveRecord::Migration
  def self.up
    create_table :courses do |t|
      t.string :name
      t.text :description
      t.bigint :student_id

      t.timestamps
    end
  end

  def self.down
    drop_table :courses
  end
end

2)查找与名称course项目目录新创建的模型和关联添加到文件:

belongs_to :student

3)查找项目文件夹中的学生模型和的has_many协会添加到:

has_many :students

4)在你的终端,cd到项目文件夹,然后运行rake db:migrate

你应该是好后去!下面是为Rails 2.3的关联参考:https://guides.rubyonrails.org/v2.3/association_basics.html

© www.soinside.com 2019 - 2024. All rights reserved.