繁体   English   中英

我需要为这些关联添加哪些引用,foreign_key?

[英]What references, foreign_keys do I need to add for these associations?

我的Rails 4.2应用程序中有这些关联。 我不明白如何在教师和课程之间设置适当的参考/ foreign_key。

到目前为止,讲师和课程表都具有local_id(本地参考)。 Local是他们俩都属于的培训中心。

class Local < ActiveRecord::Base
  has_many :instructors
  has_many :courses
end

class Instructor < ActiveRecord::Base
  belongs_to :local
  has_many :courses, through: :locals
end

class Course < ActiveRecord::Base
  belongs_to :local
  has_many :instructors, through: :locals
end

是否在课程表中添加一个foreign_key? 像这样:

add_foreign_key :courses, :instructors

我读到一些有关在有许多对许多关联时需要“联接表”的信息,因为我们需要存储许多ID。 我想本地就是这种情况。

还是我需要另一个表belongs_to :instructor, :coursebelongs_to :instructor, :course表(模型)?

这是我将其设置为最大灵活性的方式。

讲师和课程

让我们用我们称为“ Employment的联接模型建立多对多关系。

我们可以使用以下方法生成模型:

rails g model employment instructor:belongs_to course:belongs_to

这将给我们:

class Employment < ActiveRecord::Base
  belongs_to :instructor
  belongs_to :course
end

employments将具有instructor_id course_idcourse_id外键。 这使我们可以为课程分配任意数量的教练,反之亦然。

因此,让我们使用联接模型:

class Instructor < ActiveRecord::Base
  has_many :employments
  has_many :courses, through: :employments
end

class Course < ActiveRecord::Base
  has_many :employments
  has_many :instructors, through: :employments
end

场地与课程

我建议您重命名您的Local模型Venue因为它是举办课程或活动的地方的通用英语术语。 Locale很尴尬,因为它与Web应用程序中的一个单独概念冲突,并可能导致名称冲突。

而且我们可能应该将其设置为多对多,以说明现实生活中的复杂性。

再说一遍:

rails g model booking venue:belongs_to course:belongs_to

class Booking < ActiveRecord::Base
  belongs_to :venue
  belongs_to :course
end

bookings中将带有venue_idcourse_id外键。

class Venue < ActiveRecord::Base # was Local
  has_many :bookings
  has_many :courses, through: :bookings
end

class Course < ActiveRecord::Base
  # ...
  has_many :bookings
  has_many :venues, through: :bookings
end

更多阅读:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM