2010-02-24 84 views
14

我正在開發一個應用程序,使用年模型和課程模型。目前有一個has_and_belongs_to_many關係鏈接這些與courses_years表,但我想在courses_years表中存儲額外的字段。向連接表添加額外數據 - Rails

新字段是一個布爾值,稱爲「強制」。

有沒有一個簡單或很好的方式做到這一點?

回答

13

切換到使用:has_many => :through關聯,該關聯是專門爲需要連接模型時設計的。在ActiveRecord Associations Rails Guide有更多的細節。

+0

非常感謝,我的後續問題有什麼想法? http://stackoverflow.com/questions/2328273/add-fields-for-has-many-through-relationship-extra-data-rails – Jack 2010-02-24 18:14:00

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 

每當你需要的屬性(在這種情況下,強制性)您通常通過加盟模式訪問它。如果你想找到一年中所有強制課程,這個問題的答案是here

+0

非常感謝,我去選項作爲連接表的名稱。然而,我無法將布爾值添加到我的新課程表單中。有任何想法嗎? http://stackoverflow.com/questions/2328273/add-fields-for-has-many-through-relationship-extra-data-rails – Jack 2010-02-24 18:12:58

+3

模型類名稱應該是單數形式:課程 - >課程;年 - >年;課程年 - >課程年 – 2014-11-04 04:44:08