0

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.

goal.rb

class Goal < ActiveRecord::Base
  has_many :goal_activities
  has_many :activities, through: :goal_activities
end

goal_activity.rb

class GoalActivity < ActiveRecord::Base
  belongs_to :goal
  belongs_to :activity
end

activity.rb

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.

Goals

goal_id: 1, xp: 500, total_goal_xp: default 0

Activities

activity_id: 1, quantity: 3, goal_id: 1

Goal_activities

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.

1 Answer 1

0

You can use after_create callback in your activity.rb as

after_create :set_total_xp

private

def set_total_xp
  goal_activity = self.goal_activities.where(goal_id: goal_id).first_or_initialize
  goal_activity.update_attribute(:total_xp, (quantity*goal.xp))
end
Sign up to request clarification or add additional context in comments.

10 Comments

I'm assuming this would be in the goal_activities model? Would I still need to initialize the goal_id or activity_id anywhere in the same class? Also does the goal_activities know that the on_create method should be executed when the activity is created and not the goal?
nope, it should be in activity model...I am assuming here that the associated models are created already..
belongs_to association doesn't need through, remove it
Thank you. When I create an activity now, I'm getting an error message saying "undefined method `update_attributes' for #<ActiveRecord::AssociationRelation []> Did you mean? update_all". Any idea why that might be?
my bad...check the update and it is update_attribute not attributes
|

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.