开发者

Add extra data to the join table - Rails

开发者 https://www.devze.com 2022-12-20 23:16 出处:网络
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 stor

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 thi开发者_开发百科s?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消