为什么 foreign_key 被忽略了?

Why is foreign_key ignored?

我有 2 个模型与 has_onehas_many 关联。

realm.rb

class Realm < ActiveRecord::Base
    has_one :realm_type, foreign_key: "id"
end

realm_type.rb

class RealmType < ActiveRecord::Base
    has_many :realms, foreign_key: "realm_type_id"
end

但是当我在 rails console 中执行 sql 请求 Realm.find(1).realm_type 时,我得到

Realm Load (0.3ms)  SELECT "realms".* FROM "realms" WHERE "realms"."id" =   [["id", 1]]
RealmType Load (0.3ms)  SELECT  "realm_types".* FROM "realm_types" WHERE "realm_types"."id" =  LIMIT 1  [["id", 1]]

如您所见,它忽略了 foreign_key: "realm_type_id" 对于 realm_type.rb

中的 has_many 关联

更新 1:has_many 替换为 belongs_to,仍然得到相同的结果

你不应该使用 belongs_to 吗?

class RealmType < ActiveRecord::Base
  has_many :realms, foreign_key: "realm_type_id"
end

class Realm < ActiveRecord::Base
  belongs_to :realm_type
end