Ruby on Rails:从另一个模型调用实例方法

我有一个Match模型和一个团队模型。 我希望在保存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 

它的工作原理。 现在我需要在保存匹配时运行它。 所以我尝试了这个:

match.rb

 after_save :Team.goals_sum after_destroy :Team.goals_sum 

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

你可以在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 
 after_save :notify_team after_destroy :notify_team private def notify_team Team.goals_sum end