1
votes

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
1
You can't specify multiple associations with the same name (courses). Not sure if that's what you're after here, though?polarblau
Yeah, I guess what I should do is change the name of the "course" and "school" id fields in both of the the relationship tables, and then specify a foreign keyBill W.

1 Answers

1
votes

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.