Jack
Jack

Reputation: 3878

Add extra data to the join table - Rails

I am developing an application, with a years model and a courses model. Currently there is a has_and_belongs_to_many relationship linking these with a courses_years table, however I would like to store an extra field in the courses_years table.

The new field is a boolean value called "compulsory".

Is there an easy or nice way of doing this?

Upvotes: 15

Views: 11535

Answers (2)

jamuraa
jamuraa

Reputation: 3419

You want a join model. I would call it "CoursesYear" because then you don't need to change your table name, but you can also move all that data to another model if you like. Your models will be setup like this:

class Courses < ActiveRecord::Base
  has_many :courses_years
  has_many :years, :through => :courses_years
end

class Years < ActiveRecord::Base 
  has_many :courses_years
  has_many :courses, :through => :courses_years
end

class CoursesYears < ActiveRecord::Base
  belongs_to :course
  belongs_to :year
end

Whenever you need the attributes (compulsory in this case) you normally access it through the join model. If you want to just find all courses which are compulsory for a given year, the question is answered here.

Upvotes: 13

John Topley
John Topley

Reputation: 115362

Switch to using a :has_many => :through association, which is specifically designed for when you need a join model. There are more details in the ActiveRecord Associations Rails Guide.

Upvotes: 15

Related Questions