Belongs_to与主键和外键关联

时间:2014-04-02 03:50:11

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

所以我正在做一个应用程序,我有一个" Game"来自4个不同用户的4个属性的模型。其中一个属性是player_id,另外三个是用户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关系在某些方面是否有误?

1 个答案:

答案 0 :(得分:1)

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