【问题标题】:Ruby on Rails - Double association databaseRuby on Rails - 双关联数据库
【发布时间】:2014-09-20 21:23:27
【问题描述】:

我有这种情况:

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

谢谢

【问题讨论】:

  • 用户和物品是什么关系?请提及这三者之间的关系。

标签: ruby-on-rails ruby database associations


【解决方案1】:

这个怎么样?

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

【讨论】:

    【解决方案2】:

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

    您是否尝试过,在您的 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 阅读有关范围的更多信息。

    祝你好运!

    【讨论】:

      【解决方案3】:

      既然一个游戏既有 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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-21
        相关资源
        最近更新 更多