fixes #2415: "Random post" causes RecordNotFound exceptions

This commit is contained in:
r888888888
2017-01-18 14:12:12 -08:00
parent a919da4dd6
commit bfa56a860c
4 changed files with 27 additions and 24 deletions

View File

@@ -93,7 +93,7 @@ class PostsController < ApplicationController
def random
count = Post.fast_count(params[:tags], :statement_timeout => CurrentUser.user.statement_timeout)
@post = Post.tag_match(params[:tags]).reorder("").offset(rand(count)).first
@post = Post.tag_match(params[:tags]).random
raise ActiveRecord::RecordNotFound if @post.nil?
respond_with(@post) do |format|
format.html { redirect_to post_path(@post, :tags => params[:tags]) }

View File

@@ -91,29 +91,9 @@ module PostSets
end
def get_random_posts
if unknown_post_count?
chance = 0.01
elsif post_count == 0
chance = 1
else
chance = per_page / post_count.to_f
end
temp = []
temp += ::Post.tag_match(tag_string).where("random() < ?", chance).reorder("").limit(per_page)
3.times do
missing = per_page - temp.length
if missing >= 1
q = ::Post.tag_match(tag_string).where("random() < ?", chance*2).reorder("").limit(missing)
unless temp.empty?
q = q.where("id not in (?)", temp.map(&:id))
end
temp += q
end
end
temp
per_page.times.inject([]) do |all, x|
all << ::Post.tag_match(tag_string).random
end.compact.uniq
end
def posts

View File

@@ -1579,6 +1579,20 @@ class Post < ActiveRecord::Base
end
module SearchMethods
# returns one single post
def random
key = Digest::MD5.hexdigest(Time.now.to_f.to_s)
random_up(key) || random_down(key)
end
def random_up(key)
where("md5 < ?", key).reorder("md5 desc").first
end
def random_down(key)
where("md5 >= ?", key).reorder("md5 asc").first
end
def pending
where("is_pending = ?", true)
end

View File

@@ -7072,6 +7072,13 @@ CREATE INDEX index_users_on_last_ip_addr ON users USING btree (last_ip_addr) WHE
CREATE UNIQUE INDEX index_users_on_name ON users USING btree (lower((name)::text));
--
-- Name: index_users_on_name_trgm; Type: INDEX; Schema: public; Owner: -
--
CREATE INDEX index_users_on_name_trgm ON users USING gin (lower((name)::text) gin_trgm_ops);
--
-- Name: index_wiki_page_versions_on_updater_ip_addr; Type: INDEX; Schema: public; Owner: -
--
@@ -7441,3 +7448,5 @@ INSERT INTO schema_migrations (version) VALUES ('20170112021922');
INSERT INTO schema_migrations (version) VALUES ('20170112060921');
INSERT INTO schema_migrations (version) VALUES ('20170117233040');