Ruby on Rails: Calling an instance method from another model

社会主义新天地 提交于 2019-12-07 14:13:50

问题


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?


回答1:


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



回答2:


after_save :notify_team
after_destroy :notify_team

private

def notify_team
  Team.goals_sum
end


来源:https://stackoverflow.com/questions/14278113/ruby-on-rails-calling-an-instance-method-from-another-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!