Ruby on Rails:奇怪的投票增量行为 [英] Ruby on Rails: strange voting increment behavior

查看:73
本文介绍了Ruby on Rails:奇怪的投票增量行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有一个up和downvote按钮,可将一个值为1或-1的投票插入数据库。这可以正常工作。然后,我通过汇总该元素的投票值来显示该元素的总投票数。但是,这不能正常工作,因为总和显示的效果确实很奇怪:

So I have an up and a downvote button that inserts a vote with a value of 1 or -1 into the database. This works correctly. Then, I display the total vote count for that element by summing up its votes' values. However, this isn't working correctly, because the vote sum display is acting really strange:

视频的第一次投票似乎根本无法增加它。然后进行第二次投票。如果我从上投票转到下投票,则它会递增一次,然后下一个下投票就会下降。这很难解释,但是也许您可以弄清楚我的代码出了什么问题。

The first vote on a video doesn't seem to increment it at all. Then the second vote does. If I go from an upvote to a downvote, it increments up once, and then the next downvote is down. This is difficult to explain, but maybe you can figure out what is wrong with my code.

我在视频模型中拥有此功能(已投票的元素,它has_many video_votes):

I have this function in my Video model (the element that is voted on, it has_many video_votes):

def vote_sum
  read_attribute(:vote_sum) || video_votes.sum(:value)
end

我在VideoVote模型中也有此功能:

I also have this in my VideoVote model:

after_create :update_vote_sum

private

  def update_vote_sum
    video.update_attributes(:vote_sum => video.vote_sum + value)
  end

什么我做错了吗?

推荐答案

很难看出所有代码,但我会尝试更改 vote_sum

Hard to tell without seeing all the code but I would try changing vote_sum

def vote_sum
  video_votes.sum(:value)
end

...以查看关联是否工作正常。这样,您就可以将问题缩小为视频对象的 vote_sum 缓存列。

...to see if the association is working fine. That way you've narrowed the issue down to being the Video object's vote_sum cache column.

您也可以尝试以下是在导致问题的情况下替代overlay_sum属性的方法:

You could also try the following instead of overidding the vote_sum attribute in case that's causing issues:

def total_vote_sum
  vote_sum || video_votes.sum(:value)
end

我假设控制器/视图/ js逻辑都是正确的。使用Cucumber之类的工具进行测试驱动开发的经典案例,但这完全是其他讨论。

I'm assuming the controller / view / js logic is all correct. Classic case for test driven development using a tool like Cucumber, but that's a whole other discussion lol.

这篇关于Ruby on Rails:奇怪的投票增量行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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