【发布时间】:2018-08-20 16:57:57
【问题描述】:
我有:
gem 'rails', '~> 5.1.1'
gem 'mongoid', '~> 6.1.0'
我有 3 个模型,与这个问题有关。
class Book
include Mongoid::Document
field :name, type: String
field :author, type: String
field :description, type: String
field :status, type: String
field :image, type: String
has_many :histories, dependent: :destroy
has_many :likes, dependent: :destroy
has_many :comments, dependent: :destroy
def ordered_histories
histories.order(taken_in: :desc)
end
def book_rating
rating_array = likes.map { |like| like.rate.to_i }
return 0 if rating_array.empty?
(rating_array.sum / rating_array.size).round
end
end
class Like
include Mongoid::Document
field :rate, type: Integer
belongs_to :book
belongs_to :user
end
class History
include Mongoid::Document
field :taken_in, type: DateTime
field :returned_in, type: DateTime
belongs_to :book
belongs_to :user
end
我需要获得点赞和历史最多的前 5 本书。
据我所知 - mongoid 不支持连接。 我考虑过在 Book 模型中存储 likes_count 和 histories_count 。但我认为这不是最好的方法。请帮助我找到更好的解决方案,从 mongodb 获得前 5 本书。
【问题讨论】:
标签: ruby-on-rails database mongodb mongoid relationship