class Game < ActiveRecord::Base
has_many :game_types, :dependent => :destroy
has_many :types, :through => :game_types
end
class Type < ActiveRecord::Base
has_many :game_types, :dependent => :destroy
has_many :games, :through => :game_types
end
Game Type 1 == Single Player Game Type 2 == Multiplayer
游戏类型1 ==单人游戏类型2 ==多人游戏
How can I query for Games that have either type IDs 1 OR 2 OR both?
如何查询类型ID为1或2或两者的游戏?
Additionally, how can I query for Games that have neither?
另外,我如何查询没有的游戏?
This is being used with pagination via will_paginate so single queries would be preferable.
这通过will_paginate与分页一起使用,因此单个查询将更可取。
Thank you in advance for rescuing my sanity.
提前感谢您拯救我的理智。
1 个解决方案
#1
3
In rails you can always resort to just simple SQL. OR is not yet implemented fully in Arel (last I checked) so what you want is similar to this:
在rails中,您始终可以使用简单的SQL。 OR尚未在Arel中完全实现(我最后检查过),所以你想要的是这样的:
Game.joins("game_types ON (game_types.game_id = games.id)").where("game_types.id IN (1,2)")
This way the query is still reasonably performant. You can expand this a bit to not include direct references to the Ids, but that's up to you.
这样查询仍然具有合理的性能。您可以稍微扩展一下,不要包含对ID的直接引用,但这取决于您。
#1
3
In rails you can always resort to just simple SQL. OR is not yet implemented fully in Arel (last I checked) so what you want is similar to this:
在rails中,您始终可以使用简单的SQL。 OR尚未在Arel中完全实现(我最后检查过),所以你想要的是这样的:
Game.joins("game_types ON (game_types.game_id = games.id)").where("game_types.id IN (1,2)")
This way the query is still reasonably performant. You can expand this a bit to not include direct references to the Ids, but that's up to you.
这样查询仍然具有合理的性能。您可以稍微扩展一下,不要包含对ID的直接引用,但这取决于您。