如果我有一個模型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)"
這不是我正在尋找的。我錯過了什麼?
什麼是錯誤,是什麼生成的SQL查詢樣子? – max
添加生成的SQL - 它不會出錯,但它不會返回我所期望的。 –