From d78e6f7192265d578b89b571aac7bafef8cb4c56 Mon Sep 17 00:00:00 2001 From: David Celis Date: Wed, 11 Mar 2015 11:19:33 -0700 Subject: [PATCH] Return ActiveRecord::Relations for `recommended_*` methods A supposedly database-compatible way to do this; possibly addresses #96 and #103, but I'd like user feedback first. Signed-off-by: David Celis --- lib/recommendable/rater/recommender.rb | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/lib/recommendable/rater/recommender.rb b/lib/recommendable/rater/recommender.rb index 716d15f..cc11544 100644 --- a/lib/recommendable/rater/recommender.rb +++ b/lib/recommendable/rater/recommender.rb @@ -8,7 +8,11 @@ module Recommender # @return [Array] An array of instances of your user class def similar_raters(count = 10, offset = 0) ids = Recommendable.redis.zrevrange(Recommendable::Helpers::RedisKeyMapper.similarity_set_for(id), offset, count - 1) - Recommendable.query(self.class, ids).sort_by { |user| ids.index(user.id.to_s) } + + order = ids.map { |id| "`#{Recommendable.config.user_class.table_name}`.`id` = %d DESC" }.join(', ') + order = self.class.send(:sanitize_sql_for_assignment, [order, *ids]) + + Recommendable.query(self.class, ids).order(order) end private @@ -25,7 +29,9 @@ def recommended_for(klass, count = 10, offset = 0) ids = Recommendable.redis.zrevrange(recommended_set, offset, count - 1, :with_scores => true) ids = ids.select { |id, score| score > 0 }.map { |pair| pair.first } - Recommendable.query(klass, ids).sort_by { |record| ids.index(record.id.to_s) } + order = ids.map { |id| "`#{klass.table_name}`.`id` = %d DESC" }.join(', ') + order = klass.send(:sanitize_sql_for_assignment, [order, *ids]) + Recommendable.query(klass, ids).order(order) end # Removes an item from a user's set of recommendations