15

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?

John Topley
  • 113,588
  • 46
  • 195
  • 237
Jack
  • 3,878
  • 15
  • 42
  • 72

2 Answers2

15

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.

John Topley
  • 113,588
  • 46
  • 195
  • 237
  • Thanks a lot, any ideas for my follow up question? http://stackoverflow.com/questions/2328273/add-fields-for-has-many-through-relationship-extra-data-rails – Jack Feb 24 '10 at 18:14
13

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.

Community
  • 1
  • 1
jamuraa
  • 3,419
  • 25
  • 29
  • Thanks a lot, I went for Options as the name of the join table. However am having trouble adding the boolean value to my new courses form. Any ideas? http://stackoverflow.com/questions/2328273/add-fields-for-has-many-through-relationship-extra-data-rails – Jack Feb 24 '10 at 18:12
  • 3
    Models class names should be in singular form: Courses --> Course; Years --> Year; CoursesYears --> CourseYear – Redoman Nov 04 '14 at 04:44