Files
danbooru/app/models/favorite.rb
evazion 3ae62d08eb favorites: show favlist when hovering over favcount.
Changes:

* Make it so you can click or hover over a post's favorite count to see
  the list of public favorites.
* Remove the "Show »" button next to the favorite count.
* Make the favorites list visible to all users. Before favorites were
  only visible to Gold users.
* Make the /favorites page show the list of all public favorites,
  instead of redirecting to the current user's favorites.
* Add /posts/:id/favorites endpoint.
* Add /users/:id/favorites endpoint.

This is for several reasons:

* To make viewing favorites work the same way as viewing upvotes.
* To make posts load faster for Gold users. Before, we loaded all the
  favorites when viewing a post, even when the user didn't look at them.
  This made pageloads slower for posts that had hundreds or thousands of
  favorites. Now we only load the favlist if the user hovers over the favcount.
* To make the favorite list visible to all users. Before, it wasn't
  visible to non-Gold users, because of the performance issue listed above.
* To make it more obvious that favorites are public by default. Before,
  since regular users could only see the favcount, they may have
  mistakenly believed other users couldn't see their favorites.
2021-11-20 02:40:18 -06:00

43 lines
1.1 KiB
Ruby

class Favorite < ApplicationRecord
belongs_to :post, counter_cache: :fav_count
belongs_to :user, counter_cache: :favorite_count
validates :user_id, uniqueness: { scope: :post_id, message: "have already favorited this post" }
after_create :upvote_post_on_create
after_destroy :unvote_post_on_destroy
scope :public_favorites, -> { where(user: User.has_public_favorites) }
def self.visible(user)
if user.is_admin?
all
elsif user.is_anonymous?
public_favorites
else
where(user: user).or(public_favorites)
end
end
def self.search(params)
q = search_attributes(params, :id, :post, :user)
q.apply_default_order(params)
end
def self.available_includes
[:post, :user]
end
def upvote_post_on_create
if Pundit.policy!(user, PostVote).create?
PostVote.negative.destroy_by(post: post, user: user)
# Silently ignore the error if the user has already upvoted the post.
PostVote.create(post: post, user: user, score: 1)
end
end
def unvote_post_on_destroy
PostVote.positive.destroy_by(post: post, user: user)
end
end