我有一个Match模型和一个Team模型。 我希望在保存匹配后运行实例方法(在Team模型中编写)。这就是我所拥有的。
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
它有效。现在我需要在保存匹配时运行它。所以我尝试了这个:
after_save :Team.goals_sum
after_destroy :Team.goals_sum
它不起作用。 我知道我遗漏了一些基本的东西,但我仍然无法完成它。有什么提示吗?
答案 0 :(得分: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
答案 1 :(得分:2)
after_save :notify_team
after_destroy :notify_team
private
def notify_team
Team.goals_sum
end