我正试图为我的视图中的选择做一个散列。
现在我有一件丑陋的东西。
@platforms = {}
Platform.all.each do |platform|
@platforms[platform.name] = platform.game_updates
.includes(:game)
.where(game: {store_id: current_store.id})
.map {|game_update| [game_update.name, game_update.game.id] }
end我想要这样的东西:
@platforms = {
'Plateform America' => [['Fallout4',76896], ['Just',56774]],
'Plateform Ed' => [[Fallout3',77445],['Fallout2',75674],['Mario',45677]]
}我有两个问题。Game可以有许多GameUpdates。目前,列表显示了所有的game_updates。这就像有Fallout4.1,Fallout4.2,Fallout4.3和我只想要最后一个Games_update of Game。
其他问题是重构第一段代码。我试着和group_by一起玩,但没有成功。
谢谢
发布于 2015-12-01 19:09:55
解决这一问题的一种方法是在游戏表中保留一个外键last_game_update。这样,游戏可以有许多更新,但只有最后一次更新。
class Game < ActiveRecord::Base
has_many :game_updates
belongs_to :last_game_update, class_name: GameUpdate
end然后,以确保游戏表保持对游戏更新表的最新引用为代价,您的查询变得更简单了。
https://stackoverflow.com/questions/34026335
复制相似问题