Why is foreign_key ignored?

207 views Asked by At

I have 2 models with has_one and has_many associations.

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

But when i preforming sql request Realm.find(1).realm_type in rails console, i get

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]]

As you see, it ignores foreign_key: "realm_type_id" for has_many association in realm_type.rb

UPD 1: Replaced has_many with belongs_to, still get the same result

1

There are 1 answers

0
locoboy On BEST ANSWER

Shouldn't you be using belongs_to?

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

class Realm < ActiveRecord::Base
  belongs_to :realm_type
end