2012-11-26 111 views
0

我有兩個模型:團隊季節相關聯,這樣一個團隊可以屬於很多季節,每個賽季也可以有很多球隊。到目前爲止,我已經使用沒有ID屬性的連接表seasons_teams在模型之間使用了簡單的HABTM關係。HABTM生命週期掛鉤

現在我想爲一個關聯被刪除時添加一個鉤子,當一個團隊從季節中退出時執行。這樣做的最好方法是否將HABTM關聯轉換爲has_many /:低谷,向連接表添加ID屬性並創建將包含新的before_destroy鉤子的相應模型文件是否正確?如果是這樣,我該如何編寫遷移以將自動遞增的索引添加到我的連接表中? (還是會更好地創建索引的新連接表/模型和所有條目複製現有表格)

+0

你有沒有在連接表遷移中明確定義不添加id字段? –

+0

是:create_table:seasons_teams,:id => false do | t | ... –

回答

3

Rails Style Guide

體型的has_many:通過對has_and_belongs_to_many。使用的has_many:通過允許附加屬性驗證加盟模式

你的情況:

class SeasonTeam < ActiveRecord::Base # couldn't find a better name... 
    belongs_to :team 
    belongs_to :season 
    # the validates are not mandatory but with it you make sure this model is always a link between a Season and a Team 
    validates :team_id, :presence => true 
    validates :season_id, :presence => true 

    before_destroy :do_some_magic 

    #...  
end 

class Season < ActiveRecord::Base 
    has_many :teams, :through => :season_teams 
end 

class Team < ActiveRecord::Base 
    has_many seasons, :through => :season_teams 
end 
+0

是的,謝謝。這是我的想法。有用。我創建了一個全新的表來替換連接表並將所有現有數據複製到遷移中。 –

0

你也可以看看Rails的Association Callbacks。它提供了before_removeafter_remove回調方法,您可以使用這些回調方法來自定義行爲。