diff --git a/app/controllers/posts_controller.rb b/app/controllers/posts_controller.rb index 5ae49cd15..95b35a4f3 100644 --- a/app/controllers/posts_controller.rb +++ b/app/controllers/posts_controller.rb @@ -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]) } diff --git a/app/logical/post_sets/post.rb b/app/logical/post_sets/post.rb index 40618cce4..dee3371d6 100644 --- a/app/logical/post_sets/post.rb +++ b/app/logical/post_sets/post.rb @@ -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 diff --git a/app/models/post.rb b/app/models/post.rb index 0f671df69..52d125269 100644 --- a/app/models/post.rb +++ b/app/models/post.rb @@ -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 diff --git a/db/structure.sql b/db/structure.sql index 295fd7ca4..c3387c466 100644 --- a/db/structure.sql +++ b/db/structure.sql @@ -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'); +