将额外数据添加到连接表 – Rails

我正在开发一个应用程序,具有多年的模型和课程模型。 目前有一个has_and_belongs_to_many关系将这些与courses_years表相关联,但是我想在courses_years表中存储一个额外的字段。

新字段是一个名为“强制”的布尔值。

有这么简单或好的方法吗?

切换到使用:has_many => :through关联,这是专门为您需要连接模型时设计的。 ActiveRecord Associations Rails Guide中有更多详细信息。

你想要一个连接模型。 我称之为“CoursesYear”,因为那时你不需要更改你的表名,但如果你愿意,你也可以将所有数据移动到另一个模型。 您的模型将设置如下:

 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 

每当您需要属性(在这种情况下是强制的)时,您通常通过连接模型访问它。 如果你想找到一年中所有必修课程,这个问题在这里得到解答。