问题
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:
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
来源:https://stackoverflow.com/questions/44434641/ruby-on-rails-using-callback-to-multiply-two-objects-in-separate-tables-when-n