Ruby on rails RubyonRails-双关联数据库

Ruby on rails RubyonRails-双关联数据库,ruby-on-rails,ruby,database,associations,Ruby On Rails,Ruby,Database,Associations,我有这样的情况: 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

我有这样的情况:

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

谢谢

请发布您在每个型号中使用的关联,这将帮助我们回答您的问题

是否尝试在user.rb(用户模型)中添加关联:

has_many :games
has_many :items, through: :games
然后,您将获得所有项目,即用户拥有的所有游戏,如下所示:

user.items
item.users.where(:user_id => 1)
或者,对于您正在查找的非常具体的搜索,您可以在游戏模型中添加一个范围,位于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)
我没有测试任何一个,你必须根据你的需要看看什么适合你

我会在上读更多关于scopes的内容

祝你好运

这个怎么样

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

因为,一个游戏既有用户id也有物品id,我相信用户和物品之间也应该有关系。正如上面@Myst所指出的那样,在这种情况下,一个“有很多”的关系是理想的。即: 在用户模型中:

has_many :games
has_many :items, through: :games
在您的游戏模型中:

belongs_to :user
belongs_to :item
在您的模型中实现这一点,然后您可以尝试

user.games.where(:item_id => 13)
如果您还想要这样的东西:

user.items
item.users.where(:user_id => 1)
然后在项目模型中实现类似的关系,即:

has_many :games
has_many :users, through: :games

用户和项目之间的关系是什么?请提及这三者之间的关系。