Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: Calling an instance method from another model

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?

like image 410
Kurt Bourbaki Avatar asked May 25 '26 08:05

Kurt Bourbaki


1 Answers

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
like image 117
Andrew Haines Avatar answered May 27 '26 02:05

Andrew Haines



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!