Sam Baumgarten
Sam Baumgarten

Reputation: 2249

Rails User Membership Groups

I'm trying to make a application where a user belongs to multiple courses and multiple assignments belong to a course. I'm using devise for the user model. I want to be able to find all the courses a user belongs to and all the assignments their courses have.

Upvotes: 0

Views: 518

Answers (1)

thorsten müller
thorsten müller

Reputation: 5651

User model: has_and_belongs_to_many :course has_many :assignments, :through => :courses

Course model: has_and_belongs_to :user has_many :assignments

Assignment model: belongs_to :course

this requires an intermediate table CoursesUsers with columns user_id and course_id and column course_id in Assignment

with this give you can do things like current_user.courses current_user.assignments some_course.assignments some_course.users (assuming there is a current_user or some_course)

Read about details here: Active Record Associations Especially how to setup the has_and_belongs_to_many association

Upvotes: 1

Related Questions