我有三种型号,Player,Detail和Hero。Player有许多Details,Detail属于Hero。现在我想找回玩家所玩过的英雄。到目前为止是我想出来的。
Hero.where("id IN (SELECT hero_id FROM details WHERE player_id = 1)").group("id")我将如何为它编写一个作用域,以便我也可以将播放器传递到该范围?到目前为止,这就是我所得到的,但它只对Details进行分组。我还想计数每一个Hero,所以在最后我有x乘以Hero1,x乘以Hero2等等。
scope :heroes, ->(player) { where('player_id = ?', player.id).group("id") }这个范围在Detail模型中。我不知道它是否是最好的地方,因为我希望它返回Heroes而不是Details。
发布于 2013-09-13 14:33:31
好的,最后,在相当长的一段时间后,我想出了如何用一个范围获得最多播放的Heroes。
scope :mostplayed, ->(player) { select('details.*, count(heros.id) AS hero_count').joins(:hero).where('player_id = ?', player.id).group('hero_id').order('hero_count DESC').limit(3) }也许这不是最好的解决方案,但它确实做到了我想做的事情。
发布于 2013-09-12 20:17:16
我认为您只需要使用has_and_belongs_to_many,所以如果您使用:
player.heroes这将带来所有与那个球员相关的英雄。如果你不需要复制英雄,你可以用
player.heroes.uniq现在,有关和每一个英雄,也许你想要和多少细节有每个英雄?如果这不是你想要的,请解释得更好。
https://stackoverflow.com/questions/18769327
复制相似问题