Ruby on Rails-创建新条目时,使用回调在单独的表中将两个对象相乘 [英] Ruby on Rails - Using callback to multiply two objects in separate tables when new entry is created

查看:70
本文介绍了Ruby on Rails-创建新条目时,使用回调在单独的表中将两个对象相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个表,目标,活动和Goal_Activities.目标为xp设置了一个值,活动从用户那里获取输入.使用Activity中的on_create方法,我想将用户输入与目标xp相乘,并将其存储在目标活动"表中,这样我就可以记录每次更新,并最终将它们全部加在一起以在其中创建总目标xp.目标表.

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.

我在SO上发现了几个问题, 此处,它们涵盖了类似的主题,但我正在寻找很难理解模型文件之间的关联以及如何访问不同模型中的某些方法.

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

goal_activity.rb

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

activity.rb

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.

目标

goal_id:1,xp:500,total_goal_xp:默认0

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

活动

activity_id:1,数量:3,goal_id:1

activity_id: 1, quantity: 3, goal_id: 1

目标活动

goal_activity_id:1,goal_id:1,activity_id:1,total_xp:1500

goal_activity_id: 1, goal_id: 1, activity_id: 1, total_xp: 1500

创建活动后,将total_xp添加到目标表中的total_goal_xp中.

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.

推荐答案

您可以使用 在您的activity.rb中以

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

这篇关于Ruby on Rails-创建新条目时,使用回调在单独的表中将两个对象相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆