HABTM生命周期钩子

时间:2012-11-26 12:47:24

标签: ruby-on-rails has-and-belongs-to-many

我有两个模型:团队赛季相关联,这样一个团队可以属于很多赛季,每个赛季也可以有很多团队。到目前为止,我使用了没有ID属性的连接表seasons_teams在模型之间使用了简单的HABTM关系。

现在我想在删除关联时添加一个钩子,当一个团队退出一个赛季时执行。这样做的最佳方法是将HABTM关联转换为has_many /:trough,在连接表中添加ID属性并创建包含新的before_destroy挂钩的相应模型文件,这是否正确?如果是这样,我如何编写迁移以将自动递增的索引添加到我的连接表? (或者更好的方法是创建一个带索引的新连接表/模型并复制现有表中的所有条目)

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您还可以查看Rails'Association Callbacks。它提供了before_removeafter_remove回调方法,您可以使用这些方法来自定义行为。