当我访问模型'位置'以两种不同的方式,我得到了两个不同版本的模型。
其中一个人有location_id: nil
,其中一人有location_id: 3
2.0.0-p481 :054 > e.shifts.last.location
=> #<Location id: 35, location_id: 3, name: "Hoxton Hotel", address_1: "81 Great Eastern St", postcode: "EC2A 3HU", lng: -0.0827515, lat: 51.5256224, locatable_id: 13, locatable_type: "Shift", created_at: "2015-09-10 09:59:55", updated_at: "2015-09-11 10:18:41", radius: 5.0>
2.0.0-p481 :052 > Location.find(35)
Location Load (0.8ms) SELECT "locations".* FROM "locations" WHERE "locations"."id" = $1 LIMIT 1 [["id", 35]]
=> #<Location id: 35, location_id: nil, name: "Hoxton Hotel", address_1: "81 Great Eastern St", postcode: "EC2A 3HU", lng: -0.0827515, lat: 51.5256224, locatable_id: 13, locatable_type: "Shift", created_at: "2015-09-10 09:59:55", updated_at: "2015-09-11 10:18:41", radius: 5.0>
该模型具有这种自我指涉关联:
has_many :children, class_name: "Location", foreign_key: "location_id", dependent: :nullify
belongs_to :parent, class_name: "Location", foreign_key: "location_id"
问题是当我做Location.find(3).children时,并非所有的孩子都会回来。
答案 0 :(得分:1)
我认为ActiveRecord在外键的名称上行为不正确。也许您可以尝试更好地命名关联,例如parent
has_many :children, class_name: "Location", foreign_key: "parent_id", dependent: :nullify
belongs_to :parent, class_name: "Location", foreign_key: "parent_id"
顺便问一下,e.shifts
是什么?您可以尝试使用您的模型,现在可以Location.last
查看结果是否相同?
答案 1 :(得分:0)
这是因为在多个:one关系中,关系id位于'one'端,因为它是作为基础表上的一种外键实现的。
我认为你可能想要一个自我引用很多:很多关系,这是通过一个加入关系来实现的,它实现为一个带有id关系的表。
class Location < ActiveRecord::Base
has_many :location_relationships, :foreign_key => "child_id", :class_name => "LocationRelationship"
has_many :children, :through => :location_relationships
end
class LocationRelationship < ActiveRecord::Base
belongs_to :location, :foreign_key => "location_id", :class_name => "Location"
belongs_to :child, :foreign_key => "child_id", :class_name => "Location"
end