gpt4 book ai didi

ruby-on-rails - Belongs_to 与主键和外键的关联

转载 作者:搜寻专家 更新时间:2023-10-30 19:51:01 24 4
gpt4 key购买 nike

所以我正在做一个应用程序,其中有一个“游戏”模型,该模型具有来自 4 个不同用户的 4 个属性。其中一个属性是 player_id,另外 3 个是用户 uid(facebook 给出的字符串 id)。

两种模型都是这样的:

class Game < ActiveRecord::Base
belongs_to :player, class_name: "User"
belongs_to :gamer_one, class_name: "User", primary_key: "gamer_one", foreign_key: "uid"
belongs_to :gamer_two, class_name: "User", primary_key: "gamer_one", foreign_key: "uid"
belongs_to :gamer_three, class_name: "User", primary_key: "gamer_one", foreign_key: "uid"
end

class User < ActiveRecord::Base
has_many :games, foreign_key: 'player_id'
has_many :game_ones, class_name: 'Game', foreign_key: 'gamer_one', primary_key: 'uid'
has_many :game_twos, class_name: 'Game', foreign_key: 'gamer_two', primary_key: 'uid'
has_many :game_threes, class_name: 'Game', foreign_key: 'gamer_three', primary_key: 'uid'
end

当我转到控制台并检查 User.game_ones、User.game_twos 或 User.game.threes 时,我得到了我想要的确切关系,但如果我倒过来(Game.gamer_one、Game.gamer_two、 Game.gamer_three) 我刚得到 null,查询做错了。

知道我正在做的 belongs_to 关系是否在某些时候是错误的吗?

最佳答案

当您有匹配的关联时,这些关联的 foreign_keyprimary_key 是相同的。所以只需交换 belongs_to 关联中的 foreign_keyprimary_key

关于ruby-on-rails - Belongs_to 与主键和外键的关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22801213/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com