2015-10-08 95 views
0

如果我有一個模型Userhas_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

什麼是錯誤,是什麼生成的SQL查詢樣子? – max

+0

添加生成的SQL - 它不會出錯,但它不會返回我所期望的。 –

回答

0

我認爲你正在尋找

scope :with_suspended_games_or_no_games -> { 
    with_no_games.joins(:games).merge(Game.suspended) 
} 

查看SQL嘗試運行從鐵軌控制檯以下:

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'}) } 
+0

合併不是我想要的。這裏是它的SQL: '「SELECT \」users \「。* FROM \」users \「左外部連接遊戲ON games.user_id = users.id INNER JOIN事件ON events.game_id = games.id AND events .name ='rejected'WHERE(games.user_id IS NULL)「' –