2014-09-20 68 views
0

我有這種情況:Ruby on Rails的 - 雙人關聯數據庫

user.rb 
has_many :games 

item.rb 
has_many :games 

game.rb 
belongs_to :user, :foreign_key => 'user_id' 
belongs_to :item, :foreign_key => 'item_id' 


Item : 
id : 13 | name : "Foo" 

User : 
id : 1 | name : "Me" 

Game : 
id : 1 | user_id : 4 | item_id : 13 
id : 2 | user_id : 1 | item_id : 13 
id : 3 | user_id : 2 | item_id : 2 
id : 4 | user_id : 1 | item_id : 13 
.... 

這工作:

item=Item.find(13) 
user=User.find(1) 

user.games (returns all games with the user_id == 1) 
item.games (return all games with item_id == 13) 

但現在我想給用戶1與第13項的所有比賽,該怎麼辦我做 ?這不起作用:

user.item.games 

感謝

+0

什麼是用戶和項目之間的關係?請提一下這三者之間的關係。 – 2014-09-20 21:34:50

+0

@AaditiJain完成! – 2014-09-20 21:41:34

回答

1

這個怎麼樣?

Game.where(user_id: 1, item_id:13) 
0

請張貼您在每個模型中使用的關聯,這將有助於我們回答你的問題。

你嘗試,你user.rb(用戶模式)加入協會:

has_many :games 
has_many :items, through: :games 

,那麼你會得到所有的項目是所有遊戲的用戶有這樣的:

user.items 

,或者你正在尋找非常具體的搜索,你可以一個範圍添加到遊戲模式,在game.rb

scope :with_user, -> (user_id) { where(user_id: user_id) } 
scope :with_item, -> (item_id) { where(item_id: item_id) } 

,那麼你可以寫一個特定的搜索:

Game.with_user(1).with_item(13) 

我沒有測試任何這一點,你將不得不看到根據您的需要是什麼爲你工作。

我想了解更多關於示波器this link

祝你好運!

0

既然遊戲同時擁有user_id和item_id,我相信用戶和物品之間也應該有關係。正如上面@Myst指出的,在這種情況下,has_many-through關係是理想的。那就是: 在用戶模型:

has_many :games 
has_many :items, through: :games 

在您的遊戲模式:

belongs_to :user 
belongs_to :item 

實現,在你的模型,然後你可以嘗試

user.games.where(:item_id => 13) 

如果你還想要什麼樣這個:

item.users.where(:user_id => 1) 

然後實現在您的項目模型類似的關係也即:

has_many :games 
has_many :users, through: :games