【问题标题】:modeling associations in Rails for Course, Institute, Location在 Rails 中为课程、研究所、位置建模关联
【发布时间】:2018-07-19 21:27:26
【问题描述】:

我正在开发一个具有以下要求的应用程序:

管理员 (active_admin) 可以为机构创建课程。

实体之间的关系如下:

课程属于学院 (每门课程只能属于一个学院)。


一个Institute 可以有多个Locations,它提供各种Courses

Institute 的每个Location 可以提供多个Courses 并且每个Course 可以在多个Locations 中教授

我无法以这种方式创建实体之间的关系,因此创建新的Course 需要创建Institutes 及其Locations。如果没有InstitutesLocation,则无法创建Course

我试图实现这一目标的方式是

Course 可以在许多LocationsInstitutes 中教授。

但无法关联实体,因此创建 Course 需要创建 Institutes 及其位置。

任何帮助将不胜感激。

干杯。

【问题讨论】:

    标签: ruby-on-rails database data-modeling table-relationships


    【解决方案1】:

    首先,如果没有,请将 institute_id(整数)列添加到课程表中。为了运行rails g migration AddInstituteIDColumnToCourse institute_id:integer,这将在db/migrate 中创建一个文件,您可以在那里检查。然后运行rake db:migrate 将此更改提交到数据库。在您的Institute 模型粘贴has_many :courses 之后,在您的Course 模型粘贴belongs_to :institute 中通过这些步骤创建InstituteCourse 之间的关系。您可以通过这些步骤在LocationInstitute 之间创建相同的关系,您只需要更改这些代码的一些必要部分。

    您需要在CourseLocation 之间使用has_and_belongs_to_many 关系 为了做到这一点,首先你需要创建一个像这样rails g migration CreateJoinTableCourseLocation course_id:integer location_id:integer 的迁移文件并运行rake db:migrate 这将创建一个表来存储每个Course 在许多Location 中教授的每个@ 987654338@ 和相反的方式。在db/中检查这个迁移文件夹。然后在您的Location 模型中粘贴has_and_belongs_to_many :coursesCourse 模型has_and_belongs_to_many :locations。您可以查询在某个位置提供的每门课程:location.courses,反之则为您提供课程教授的位置course.locations。希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-20
      • 1970-01-01
      • 2014-08-25
      • 1970-01-01
      • 1970-01-01
      • 2014-07-22
      • 2010-09-22
      • 2013-03-16
      相关资源
      最近更新 更多