3

我有一个 Match 模型和一个 Team 模型。我想在保存匹配后运行一个实例方法(在 Team 模型中编写)。这就是我所拥有的。

团队.rb

def goals_sum
  unless goal_count_cache
    goal_count = a_goals_sum + b_goals_sum
    update_attribute(:goal_count_cache, goal_count)
  end
  goal_count_cache
end

它有效。现在我需要在保存比赛时运行它。所以我尝试了这个:

匹配.rb

after_save :Team.goals_sum
after_destroy :Team.goals_sum

它不起作用。我知道我缺少一些基本的东西,但我仍然无法完成它。有小费吗?

4

2 回答 2

3

您可以在Match委托给方法的方法上定义一个私有方法Team(否则,它怎么知道在哪个团队上运行该方法?您说它是一个实例方法,我假设一场比赛有正在玩它的团队)。

after_save :update_teams_goals_sum
after_destroy :update_teams_goals_sum

private

def update_teams_goals_sum
  [team_a, team_b].each &:goals_sum
end
于 2013-01-11T12:27:49.127 回答
2
after_save :notify_team
after_destroy :notify_team

private

def notify_team
  Team.goals_sum
end
于 2013-01-11T12:24:44.367 回答