我有两个has_one
和has_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
,仍会得到相同的结果
答案 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