【问题标题】:Belongs_to association with primary key and foreign keyBelongs_to 与主键和外键的关联
【发布时间】:2014-05-13 03:09:54
【问题描述】:

所以我正在做一个应用程序,其中我有一个“游戏”模型,它具有来自 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关系在某些时候是错误的吗?

【问题讨论】:

  • 交换belongs_to关联中的foreign_key和primary_key。
  • 大声笑,成功了.. 非常感谢先生!
  • 不错。我已将其添加为带有一点解释的答案。

标签: ruby-on-rails database ruby-on-rails-4 associations psql


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-27
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    • 2015-09-06
    • 2011-03-08
    相关资源
    最近更新 更多