Bhushan Lodha
Bhushan Lodha

Reputation: 6862

Creating relationship between models. Rails 3

I have two model like so

 class User < ActiveRecord::Base

   attr_accessible :email, :password, :password_confirmation, :remember_me, :fname, :lname
 end

 class Course < ActiveRecord::Base

  belongs_to :university
   attr_accessible :course_code, :department, :name, :path, :university_code, :department_code

 set_primary_key :course_code
end

now a user can take many courses and a course could have many user. Also, the join table will have some attributes like the status of course user is taking, lectures he may have completed, etc.

How do I go about creating a relationship?

Upvotes: 0

Views: 201

Answers (1)

Doodloo
Doodloo

Reputation: 919

If a Course has a "uniqueness" notion, then you would need an intermediate model (Eg. UserCourseResults), so at any given state of your database, each Course can be unique. Then, you would just organize as follows:

User:
  has_many    :user_course_results
  has_many    :courses, through: user_course_results
Course:
  has_many:   :user_course_results
  has_many:   :users, through: user_course_results
UserCourseResult:
  attr_accessible :result # So each user can have a result on each course, for instance.
  belongs_to  :user
  belongs_to: :course

Do you see the point of the intermediate model?

HTH,

Pierre.

EDIT: i just saw your edit, and i guess this is exactly what you had in mind. You have to keep in mind that a User model only hold data that are unique per-user, the same notion goes for the Course model. So the best would probably be to have this intermediate "UserCourseResult" model, that would hold any user-course specific data... This kind of relationship, when you don't need intermediate data in addition to the link between user and courses, is called HABTM (Has and belongs to many). You should have a look at this specific section in the active record doc (See has_many: through => * and has_and_belongs_to_many).

Upvotes: 2

Related Questions