简体   繁体   中英

has_many through in Ruby on Rails app

In my rails app a user can create courses and schools (group). Each time a user creates a course or school their user_id is stored in the database table for the course or school, so a user has_many :schools and :courses and the school or course belongs_to :user. Also, the user can can attend courses and join schools (as student or professor) with a has_many through relationship model (schoolgroups for schools which has a :user_id, school_id, and :role [string], and for courses student_users (and professor_users) which has a :user_id, course_id, and :role [string]. My question is, in the user model can I just specify once that:

has_many :schools, :dependent => :destroy
has_many :courses, :dependent => :destroy
has_many :schoolgroups, :dependent => :destroy
has_many :student_users, :dependent => :destroy
has_many :professor_users, :dependent => :destroy

or would I have to have a user model that looked like this:

has_many :schools, :dependent => :destroy
has_many :courses, :dependent => :destroy
has_many :schoolgroups, :dependent => :destroy
has_many :schools, :through => :schoolgroups
has_many :student_users, :dependent => :destroy
has_many :courses, :through => :student_users
has_many :professor_users, :dependent => :destroy
has_many :courses, :through => :professor_users

You'll need to think about the ownership of the models in a bit more detail. has_many means a many-to-one relationship, so saying Professor has_many Courses means that the professor owns the courses and the course only has one professor (or does it?). So you'll do something like this:

has_many :school, :dependent => :destroy
has_many :courses, :dependent => :destroy
has_many :schoolgroups, :dependent => :destroy

On the other hand, you'll have things that the user is associated to, but other users may also be associated in the same way. For example, a user can be a student in a course, but so can many other students. For this you'll want to use has_and_belongs_to_many or HABTM which represents a many-to-many relationship:

has_and_belongs_to_many :courses_as_student, :class_name => "Course",
                                             :join_table => "student_users"

Then in the Course class:

belongs_to :user

# or even better:
# belongs_to :professor, :class_name => "User", :foreign_key => "professor_id"

has_and_belongs_to_many :students, :class_name => "User",
                                   :join_table => "student_users"

You can read all the details in the Rails documentation .

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