Ruby on rails 当以不同方式访问时,获取同一模型的不同版本

Ruby on rails 当以不同方式访问时,获取同一模型的不同版本,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,当我以两种不同的方式访问模型“位置”时,我会得到模型的两个不同版本 一个有location\u id:nil,一个有location\u 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.0

当我以两种不同的方式访问模型“位置”时,我会得到模型的两个不同版本

一个有
location\u id:nil
,一个有
location\u 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> 

问题是,当我执行Location.find(3).children时,并不是所有的子项都会返回。

这是因为在多:一关系中,关系id位于“一”端,因为它是作为基础表上的外键类型实现的

我认为您可能需要一个自引用的many:many关系,这是通过拥有一个连接关系来实现的,连接关系被实现为一个具有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
类位置“子\u id”,:类名称=>“位置关系”
有多个:子项,:通过=>:位置\u关系
结束
类位置关系“location\u id”,:class\u name=>“location”
属于:child,:foreign\u key=>“child\u id”,:class\u name=>“Location”
结束

我认为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.shift
?你能试一下你的模型现在的位置吗?最后一次,看看结果是否一样?

我不明白。。。我正在寻找一种多人关系。当然,在基础表中,位置35的位置_id是否为3?
has_many :children, class_name: "Location", foreign_key: "parent_id", dependent: :nullify
belongs_to :parent, class_name: "Location", foreign_key: "parent_id"