views:

147

answers:

2

Hi,

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?

+5  A: 

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
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
+2  A: 

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.

jamuraa
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