的Ruby / Rails的 - 进行自动计算一个模型的属性 [英] Ruby/Rails - Performing automatic calculations for a models attributes

查看:407
本文介绍了的Ruby / Rails的 - 进行自动计算一个模型的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

进出口工作在轨道创造一个游戏,我遇到了一个问题,创造得分的逻辑。

Im working on creating a game in rails and I ran into a problem for creating the scoring logic.

我有一个模型叫分数属于一个用户,并具有total_points为属性。

I have a model called Score which belongs to a user and has total_points as an attribute.

所以每次用户创建一个职位(或其他)我想自动调整用户total_score属性。

So every time a user creates a post(or whatever) I would like to automatically adjust the users total_score attribute.

我有,我可以在计分模型的地方创建一个方法,但都没有这样做过,所以我有点糊涂了的感觉。

I have a feeling that I could create a method somewhere in the score model but haven't done this before so I'm a bit confused.

推荐答案

这是很好的用例的ActiveRecord的回调。

This is good use case for a ActiveRecord callback.

#post.rb

  belongs_to :score

  after_create :update_total_score

  protected

  def update_total_score
    score.update_attribute :total_score, score.total_score + new_score_value
  end

请注意:如果帖子是可更新的,那么你可能需要使用after_save的,但我的猜测是after_create是你在找什么

Note: if the post is updatable, then you would want to use after_save, but my guess is after_create is what you are looking for

祝你好运!

这篇关于的Ruby / Rails的 - 进行自动计算一个模型的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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