Answer the question
In order to leave comments, you need to log in
How to sort posts by rating in mongoid?
There is a model Post.rb It is
necessary to sort by rating
class Post
field :vote_count, type: Integer
field :published_at, type: Time
def rating
(vote_count -1) / (( hours_past + 2) ** 1.5)
end
def hours_past
(Time.now - self.published_at)/3600
end
end
Answer the question
In order to leave comments, you need to log in
And here is the mongoid if the field by which you need to sort is not stored in the database, with this logic, use the usual sorting of the array
Sorry, but you have several mistakes here at once:
1. In the initial conditions, the rating is negative, which is somewhat strange. Usually the initial rating should be 0. -1 is a mistake - it's better to just forbid voting for yourself.
2. With this approach, you need aggregations. Only in this case I would at least limit the search by date, and by the number of votes.
The reason is that there is no magic here - aggregations are quite difficult to calculate, and it makes no sense to dig with them for the sake of rating several hundred thousand topics with 10 years ago.
See an example here: stackoverflow.com/questions/20585135/mongodb-get-a...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question