当我以两种不同的方式访问模型“位置”时,我会得到该模型的两个不同版本。
一个有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 时,并不是所有的 child 都会回来。
最佳答案
我不认为 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
并查看结果是否相同?
关于ruby-on-rails - 以不同方式访问时,得到相同模型的不同版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32767594/