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
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:
Then you can fetch all paintings like this way:
@paintings = Painting.all.order_by_maximum_votes