Files
danbooru/app/models/post_vote.rb
evazion 3dc854c0c8 post_vote.rb: determine vote magnitude from voter, not CurrentUser.
Bug: when moving favorites, the parent is given an upvote for each gold+
favoriter, but the magnitude of these upvotes was based on the
CurrentUser, rather than the upvoter. This meant that upvotes for
supervoter favorites weren't given correctly.

To fix this, `magnitude` is changed to use the voting `user` instead of
CurrentUser.

New problem: when setting the score, `score=` calls `magnitude`, but
`user` isn't initialized yet. So we also refactor so that

    1. `initialize_attributes` initializes `user` before setting `score`
    2. the vote direction is given by `vote`, so it's separate from `score`
    3. updating the score on the post happens in a callback instead of
       directly in `score=`.
2017-03-24 15:43:55 -05:00

65 lines
1.8 KiB
Ruby

class PostVote < ActiveRecord::Base
class Error < Exception ; end
belongs_to :post
belongs_to :user
attr_accessor :vote
attr_accessible :post, :post_id, :user, :user_id, :score, :vote
after_initialize :initialize_attributes, if: :new_record?
validates_presence_of :post_id, :user_id, :score
validates_inclusion_of :score, :in => [SuperVoter::MAGNITUDE, 1, -1, -SuperVoter::MAGNITUDE]
after_create :update_post_on_create
after_destroy :update_post_on_destroy
def self.prune!
where("created_at < ?", 90.days.ago).delete_all
end
def self.positive_user_ids
select_values_sql("select user_id from post_votes where score > 0 group by user_id having count(*) > 100")
end
def self.negative_post_ids(user_id)
select_values_sql("select post_id from post_votes where score < 0 and user_id = ?", user_id)
end
def self.positive_post_ids(user_id)
select_values_sql("select post_id from post_votes where score > 0 and user_id = ?", user_id)
end
def initialize_attributes
self.user_id ||= CurrentUser.user.id
if vote == "up"
self.score = magnitude
elsif vote == "down"
self.score = -magnitude
end
end
def update_post_on_create
if score > 0
Post.where(:id => post_id).update_all("score = score + #{score}, up_score = up_score + #{score}")
else
Post.where(:id => post_id).update_all("score = score + #{score}, down_score = down_score + #{score}")
end
end
def update_post_on_destroy
if score > 0
Post.where(:id => post_id).update_all("score = score - #{score}, up_score = up_score - #{score}")
else
Post.where(:id => post_id).update_all("score = score - #{score}, down_score = down_score - #{score}")
end
end
def magnitude
if user.is_super_voter?
SuperVoter::MAGNITUDE
else
1
end
end
end