2013-02-05 14:16:51 -05:00
|
|
|
class CategoryFeaturedUser < ActiveRecord::Base
|
|
|
|
belongs_to :category
|
|
|
|
belongs_to :user
|
|
|
|
|
|
|
|
def self.max_featured_users
|
2013-02-07 10:45:24 -05:00
|
|
|
5
|
2013-02-05 14:16:51 -05:00
|
|
|
end
|
|
|
|
|
2014-01-29 18:32:04 -05:00
|
|
|
def self.feature_users_in(category_or_category_id)
|
|
|
|
category_id =
|
2017-04-15 00:11:02 -04:00
|
|
|
if category_or_category_id.is_a?(Integer)
|
2014-01-29 18:32:04 -05:00
|
|
|
category_or_category_id
|
|
|
|
else
|
|
|
|
category_or_category_id.id
|
|
|
|
end
|
|
|
|
|
2013-12-18 10:51:26 -05:00
|
|
|
# Figure out most recent posters in the category
|
|
|
|
most_recent_user_ids = exec_sql "
|
|
|
|
SELECT x.user_id
|
|
|
|
FROM (
|
|
|
|
SELECT DISTINCT ON (p.user_id) p.user_id AS user_id,
|
|
|
|
p.created_at AS created_at
|
|
|
|
FROM posts AS p
|
|
|
|
INNER JOIN topics AS ft ON ft.id = p.topic_id
|
|
|
|
WHERE ft.category_id = :category_id
|
|
|
|
AND p.user_id IS NOT NULL
|
|
|
|
ORDER BY p.user_id, p.created_at DESC
|
|
|
|
) AS x
|
|
|
|
ORDER BY x.created_at DESC
|
|
|
|
LIMIT :max_featured_users;
|
2014-01-29 18:32:04 -05:00
|
|
|
", category_id: category_id, max_featured_users: max_featured_users
|
|
|
|
|
2017-07-27 21:20:09 -04:00
|
|
|
user_ids = most_recent_user_ids.map { |uc| uc['user_id'].to_i }
|
2014-01-29 18:32:04 -05:00
|
|
|
current = CategoryFeaturedUser.where(category_id: category_id).order(:id).pluck(:user_id)
|
|
|
|
|
|
|
|
return if current == user_ids
|
2013-02-05 14:16:51 -05:00
|
|
|
|
|
|
|
transaction do
|
2014-01-29 18:32:04 -05:00
|
|
|
CategoryFeaturedUser.delete_all category_id: category_id
|
|
|
|
user_ids.each do |user_id|
|
|
|
|
create(category_id: category_id, user_id: user_id)
|
2013-02-05 14:16:51 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
end
|
|
|
|
|
|
|
|
end
|
2013-05-23 22:48:32 -04:00
|
|
|
|
|
|
|
# == Schema Information
|
|
|
|
#
|
|
|
|
# Table name: category_featured_users
|
|
|
|
#
|
|
|
|
# id :integer not null, primary key
|
|
|
|
# category_id :integer
|
|
|
|
# user_id :integer
|
2014-08-27 01:19:25 -04:00
|
|
|
# created_at :datetime not null
|
|
|
|
# updated_at :datetime not null
|
2013-05-23 22:48:32 -04:00
|
|
|
#
|
|
|
|
# Indexes
|
|
|
|
#
|
|
|
|
# index_category_featured_users_on_category_id_and_user_id (category_id,user_id) UNIQUE
|
|
|
|
#
|