diff --git a/app/controllers/items_controller.rb b/app/controllers/items_controller.rb index 06e5c3e..3efc0ed 100644 --- a/app/controllers/items_controller.rb +++ b/app/controllers/items_controller.rb @@ -4,7 +4,7 @@ class ItemsController < ApplicationController before_action :set_user_item, only: [:edit, :update, :toggle] def index - order = params[:newest] ? {created_at: :desc} : {score: :desc} + order = params[:newest] ? {created_at: :desc} : {rank: :desc} @items = Item.order(order).includes(:user) @votes = @items.includes(:votes).each_with_object({}) do |item, object| diff --git a/app/controllers/user_item_votes_controller.rb b/app/controllers/user_item_votes_controller.rb index 51c090a..bc4927c 100644 --- a/app/controllers/user_item_votes_controller.rb +++ b/app/controllers/user_item_votes_controller.rb @@ -1,5 +1,5 @@ class UserItemVotesController < ApplicationController - before_action :set_item + before_action :set_item, :require_login def create if current_user.votes.build(vote_params).save diff --git a/app/models/vote.rb b/app/models/vote.rb index ae7f5c0..a7e3259 100644 --- a/app/models/vote.rb +++ b/app/models/vote.rb @@ -22,9 +22,20 @@ def get_object def update_votes attrs = self.attributes.with_indifferent_access.slice(:votable_id, :votable_type) count = Vote.where(attrs).count - get_object.update( + item = get_object + + # Hot Score is a function defined inside: + # db/migrate/20150405200823_add_hot_score_function.rb + + rank = item.class.where(id: item.id) + .select("id, hot_score(#{count}, 0, created_at) as hot_score") + .first.hot_score.to_i + + item.update( + downvotes_count: 0, upvotes_count: count, - score: count + score: count, + rank: rank ) end end diff --git a/db/migrate/20150405200823_add_hot_score_function.rb b/db/migrate/20150405200823_add_hot_score_function.rb new file mode 100644 index 0000000..1bc0a3c --- /dev/null +++ b/db/migrate/20150405200823_add_hot_score_function.rb @@ -0,0 +1,18 @@ +class AddHotScoreFunction < ActiveRecord::Migration + # This is some sql borrowed from reddit: + # https://github.com/reddit/reddit/blob/master/sql/functions.sql + def up + execute <<-SQL + create or replace function + hot_score(ups integer, downs integer, date timestamp with time zone) + returns numeric as $$ + select round(cast(log(greatest(abs($1 - $2), 1)) * sign($1 - $2) + + (date_part('epoch', $3) - 1134028003) / 45000.0 as numeric), 7) + $$ language sql immutable; + SQL + end + + def down + execute "DROP FUNCTION IF EXISTS hot_score(integer, integer, timestamp);" + end +end diff --git a/db/schema.rb b/db/schema.rb index 659cf1f..4a90053 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -11,7 +11,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 20150216170958) do +ActiveRecord::Schema.define(version: 20150405200823) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql"