0

我在我的rails 应用程序中使用acts_as_votabledevise_invitable 。

用户可以发表评论,他们的评论是可投票的。

每个用户都有一个业力/分数

目前我在他们的个人资料上显示用户业力。我实际上并没有将他们的分数保存在数据库中。我只是用这个来计算它:

<% comment_vote_count = current_user.comments.map{|c| c.votes.count}.sum
   comment_vote_count ||=0 
   comment_vote_count *= 2
   total_vote_count = comment_vote_count + current_user.base_score %>

base_score 充当可以手动更改的锚点。

我希望在评分机制中添加一些内容。对于他们邀请的每个实际接受邀请并注册的用户,我想为任何给定用户添加 10 分。

所以计算用户业力的新逻辑应该是评论获得的票数乘以2,每次邀请成功加10分,再加上基础分数。

更重要的是如何将其保存在数据库中?我想在用户表中添加一个名为 score 的列。但是如何让它更新呢?每次用户加载他们的个人资料时,我是否让控制器更新它?

4

1 回答 1

1

这是一个简单的计划。首先,score在表格中添加一列users

在您的User模型中:

after_invitation_accepted :increment_score_of_inviter

def increment_score_of_inviter
  invitation_by.increment!(:score, 10)
end

def comment_vote_count
  Vote.find(comment_ids).count * 2
end

def calculated_vote_count
  base_score + comment_vote_count
end

def recalculate_score!
  update_attribute(:score, calculated_vote_count)
end

请参阅设计的邀请回调关于after_invitation_accepted

如果您有很多投票活动,这可能会非常低效,但要保持score列更新,请将其添加到您的Vote模型中:

after_create :increment_user_score

def increment_user_score
  user.increment!(:score, 2)
end

这里的另一种选择是定期重新计算score列,可能使用whenevergem:

every :hour do
  User.find_each { |u| u.recalculate_score! }
end
于 2014-04-16T23:22:43.747 回答