简体   繁体   中英

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

I have these associations in my Rails 4.2 app. I don't understand how to setup the proper references/foreign_keys between instructors and courses.

So far both instructors and courses tables have a local_id (local reference). Local is a training center they both belong to.

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

Do I add a foreign_key to the courses table? Like this:

add_foreign_key :courses, :instructors

I read something about when having many to many associations we need a "join table" cause we need to store many ids. I guess Local is just that in this case.

Or do I need another table(Model) that belongs_to :instructor, :course ?

Here is how I would set it up for maximum flexibility.

Instructors and Courses

Lets set up a many to many relationship with a join model which we call Employment .

We can generate the model with:

rails g model employment instructor:belongs_to course:belongs_to

Which will give us this:

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

employments will have the instructor_id and course_id foreign keys. This lets us assign any number of instructors to a course and vice versa.

So let's put the join model to use:

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

Venues and Courses

I would recommend you rename your Local model Venue as it's the common english term for the place where a course or event is held. Locale is awkward since it collides with a separate concept in web applications and may cause name clashes.

And we should probably set it up as many to many to account for the complexities of real life.

So again:

rails g model booking venue:belongs_to course:belongs_to

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

bookings will have the venue_id and course_id foreign keys.

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

More reading:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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