1

Ok, So I have a review model, and a votes model (Upvotes and Downvotes modeled through a single variable 'likes', If its true its an upvote, if its false its a downvote.). The votes are a has_many relation, and are polymorphic (I hope to be able to use this on more than just reviews later on).

So in the reviews model has the line

 has_many :votes, :as => :votable

And the votes model is defined like this

class Vote < ActiveRecord::Base
  belongs_to :votable, :polymorphic => true
  belongs_to :user

  def upvote?
    like
  end

  def downvote?
    !like
  end
end

Now this is fine, I can upvote, downvote and remove votes just fine. But I'm trying to generate a score bassed on the upvotes and downvotes (Simply upvotes-downvotes for now). To do this I added the following to the reviews model

def score
  up = 0
  down = 0
  self.votes.each do |v|
    if v.upvote?
      up += 1
    elsif v.downvote?
      down += 1
    end
  end
  up-down
end

However I always get 0 back as the answer. The error is in the loop, as I can set the up or down variables to be what ever outside of it and they are passed through. Its starting to drive me insane, and I have no idea where im going wrong.

4

2 回答 2

1

对于初学者来说,最好使用数据库来计算具有命名范围的反对和赞成的数量。

然后,一旦获得总计数,您就可以从赞成票中减去反对票。

有关范围的更多信息,请参阅: http: //guides.rubyonrails.org/active_record_querying.html#scopes

于 2012-05-28T23:04:40.977 回答
0

如果您确定错误在循环中,那么这是我最好的猜测:

你有 v.upvote 吗?好像,和 v.downvote?作为一个 elsif。

如果这两个都是假的会发生什么?我很确定什么都不会发生。因此,0 - 0 = 0,你总是得到零。如果您的 v.upvote? 和 v.downvote?写得正确,或者它们是正确的值。

尝试:

if v.upvote?
 ...
else
 ...
end

显然,您以这种方式进行这些设置是有原因的,但您可能只是在错误的事情上进行分区。

希望这可以帮助。

于 2012-05-29T03:47:18.887 回答