Fix #4867: random=true in api only returns one post.

Pundit 2.1.1 changed it so that if the first argument to `authorize` is
an Array, then the `authorize` call returns the last element of the
array. This broke order:random, because in that case we returned an
Array of posts. The fix is to return an ActiveRecord::Relation of posts,
which is more correct anyway.
This commit is contained in:
evazion
2021-08-29 22:37:16 -05:00
parent 46c1b2c37d
commit 1e5c7d6f0f
3 changed files with 18 additions and 2 deletions

View File

@@ -115,7 +115,7 @@ module PostSets
@post_count = get_post_count
if is_random?
get_random_posts
get_random_posts.paginate(page, search_count: false, limit: per_page, max_limit: max_per_page).load
else
normalized_query.build.paginate(page, count: post_count, search_count: !post_count.nil?, limit: per_page, max_limit: max_per_page).load
end

View File

@@ -1145,11 +1145,18 @@ class Post < ApplicationRecord
end
module SearchMethods
# Return a set of up to N random posts. May return less if there aren't
# enough posts.
#
# @param n [Integer] The maximum number of posts to return
# @return [ActiveRecord::Relation<Post>]
def random(n = 1)
n.times.map do
posts = n.times.map do
key = SecureRandom.hex(16)
random_up(key) || random_down(key)
end.compact.uniq
find_ordered(posts.map(&:id))
end
def random_up(key)