3

I've got a Match model and a Team model. I want to run an instance method (written inside the Team model) after a Match has been saved. Here's what I've got.

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

and it works. Now I need to run this whenever a match gets saved. So I tried this:

match.rb

after_save :Team.goals_sum
after_destroy :Team.goals_sum

And it doesn't work. I know I'm missing something basic, but I still can't go through with it. Any tips?

3
  • Why don't you put that in Match then? Commented Jan 11, 2013 at 12:23
  • 1
    Does the match model has 2 relations to the teams playing the match? Like team_a and team_b? Commented Jan 11, 2013 at 12:47
  • @mliebelt - Yes, it has 2 relations: belongs_to :team_a, :class_name => 'Team', :foreign_key => 'team_a_id' (and the same for :team_b) Commented Jan 11, 2013 at 14:03

2 Answers 2

3

You can just define a private method on Match that delegates to the method on Team (otherwise, how would it know which team to run the method on? You say it's an instance method, and I assume a match has teams that are playing it).

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that worked. I also had to correct a wrong part of the 'goals sum' definition in team.rb model, since it was using a wrong "unless" conditional that prevented the :goal_count_cache column in db to be updated.
2
after_save :notify_team
after_destroy :notify_team

private

def notify_team
  Team.goals_sum
end

3 Comments

That's not calling an instance method of Team.
@Alex Lang - That would give me this error: undefined method `goals_sum' for #<Class:0xb6f61344>
well, you still have to define def self.goals_sum on Team.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.