为什么外键被忽略?

时间:2015-06-08 16:14:15

标签: ruby-on-rails ruby associations models

我有两个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

但是当我在Realm.find(1).realm_type中预先形成sql请求rails console时,我得到了

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

如您所见,它会忽略 realm_type.rb中<{1}}关联的foreign_key: "realm_type_id"

UPD 1:has_many替换为has_many,仍会得到相同的结果

1 个答案:

答案 0 :(得分:3)

你不应该使用belongs_to吗?

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

class Realm < ActiveRecord::Base
  belongs_to :realm_type
end