How to list paintings based on number of votes
-
28-09-2019 - |
Pergunta
Ive got a painting model. votes is embedded into painting. How can i query all paintings and order by the number of votes? IN theory, I would like to list down all paintings starting with the ones with the most votes.
For reference purposes. Here is the definition of the two models:
class Painting
include Mongoid::Document
include Mongoid::Timestamps
field :title, :type => String
embeds_many :votes
...
end
class Vote
include Mongoid::Document
include Mongoid::Timestamps
embedded_in :painting, :inverse_of => :votes
...
end
Solução
You can do it by using counter cache column. Once you implement this functionality like mentioned here: http://railscasts.com/episodes/23-counter-cache-column, paintings table will contain votes_count column which holds the number of votes for each painting
Then you can easily add named_scope in your painting.rb model to order paintings by number of votes:
class Painting
named_scope :order_by_maximum_votes, :order => "votes_count DESC"
end
Then you can fetch all paintings like this way:
@paintings = Painting.all.order_by_maximum_votes
Outras dicas
If you still don't want to use add one more column in database, you can have another simple option. Fetch all paintings from database and then sort them by votes count:
# It fetches all paintings needed
@paintings = Painting.all
# Then sort them by number of votes
@paintings = @paintings.sort {|p| p.votes.length}