ruby-on-rails - 以不同方式访问时,得到相同模型的不同版本

标签 ruby-on-rails ruby activerecord

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

一个有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/

相关文章:

javascript - 简单表单无法在提交时关闭模式

ruby-on-rails - 为什么 Rails 拒绝使用我的模型(基于 SQL View )?

ruby-on-rails - 如何使用变量访问 erb 中 ruby​​ 对象的字段名?前任。模型.task_#{变量}

ruby - 遍历 Jekyll 集合页面的标签 - 显示时不带空格

sql - Rails ActiveRecord where 子句

sql - Rails - 删除满足条件的所有记录

ruby-on-rails - 销毁空白嵌套属性

ruby-on-rails - 替换直到删除所有匹配项

ruby-on-rails - Rails Composer 不能在 Windows 上运行。 SSL错误

ruby-on-rails - 我如何使用事件记录从 foren 表中进行选择