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

时间:2013-01-11 12:22:12

标签: ruby-on-rails ruby methods model

我有一个Match模型和一个Team模型。 我希望在保存匹配后运行实例方法(在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

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

2 个答案:

答案 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
相关问题