[英]How do I set foreign_keys on a has_many: :through association in Rails?
[英]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, :course
( belongs_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_id
和course_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_id
和course_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.