I have 3 tables, Goals, Activities and Goal_Activities. Goal has a set value for xp and Activity takes an input from the user. Using the on_create method in Activity, I'd like to multiply the user input with the goal xp and store that in the Goal Activities table so I can keep a record of each update and eventually add them all together to create a total goal xp in the Goal table.
I've found a couple of questions on SO, here and here, that cover similar topics but I'm finding it hard to get my head around the associations between the model files and how to access certain methods in different models.
I've also read the documentation on callbacks which I think is what I need to setup but if there's a better way of doing it, please let me know.
Here are my model associations at the moment.
class Goal < ActiveRecord::Base has_many :goal_activities has_many :activities, through: :goal_activities end
class GoalActivity < ActiveRecord::Base belongs_to :goal belongs_to :activity end
class Activity < ActiveRecord::Base has_many :goal_activities belongs_to :goal, through: :goal_activities end
Here are a set of example values in the tables.
goal_id: 1, xp: 500, total_goal_xp: default 0
activity_id: 1, quantity: 3, goal_id: 1
goal_activity_id: 1, goal_id: 1, activity_id: 1, total_xp: 1500
The total_xp would then be added to the total_goal_xp in the Goal table once the activity has been created.
Any advice would be appreciated. Let me know if you have any questions.