如果我有一个名为User
的模型has_many :games
和游戏has_many :events
- 如何让所有没有任何游戏的用户或任何有暂停事件的游戏。
以下是我的尝试:
示例:
用户类:
scope :with_no_games -> {
joins("LEFT OUTER JOIN games g on g.user_id = users.id").where("games.id IS NULL")
}
scope :with_suspended_games_or_no_games -> {
with_no_games.merge(Game.suspended) # <- this doesn't work
}
游戏课程:
scope :suspended -> {
joins("INNER JOIN events e ON event.game_id = games.id AND event.name = 'suspended'")
}
如果我运行User.with_suspended_games_or_no_games
,我会得到以下SQL语句:
SELECT \"users\".* FROM \"users\" LEFT OUTER JOIN games ON games.user_id = users.id INNER JOIN events ON events.game_id = games.id AND events.name = 'suspended' WHERE (games.user_id IS NULL)"
这不是我要找的。我错过了什么?
答案 0 :(得分:0)
我认为你在寻找
scope :with_suspended_games_or_no_games -> {
with_no_games.joins(:games).merge(Game.suspended)
}
看到sql尝试从rails控制台运行以下命令:
User.with_suspended_games_or_no_games.to_sql
<强>奖金强>
你也可以写下你的范围:
用户强>
scope :with_no_games -> { joins(:games).where(games: {id: nil}) }
scope :with_suspended_games_or_no_games -> { joins(:games).with_no_games.merge(Game.suspended) }
<强>游戏强>
scope :suspended -> { joins(:events).where(events: {name: 'suspended'}) }