我正在开发一个应用程序,具有多年的模型和课程模型.目前有一个has_and_belongs_to_many关系将这些与courses_years表相关联,但是我想在courses_years表中存储一个额外的字段.
新字段是一个名为"强制"的布尔值.
这样做有简单或好的方法吗?
Joh*_*ley 14
切换到使用:has_many => :through
关联,该关联专门为您需要连接模型而设计.ActiveRecord Associations Rails指南中有更多详细信息.
jam*_*raa 12
你想要一个连接模型.我称之为"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
Run Code Online (Sandbox Code Playgroud)
只要您需要属性(在这种情况下是强制的),您通常可以通过连接模型访问它.如果您想要查找特定年份的所有必修课程,请在此处回答问题.
归档时间: |
|
查看次数: |
9093 次 |
最近记录: |