多人自我加入 - 铁路自​​己的文档错了吗?

时间:2012-03-25 22:50:09

标签: ruby-on-rails activerecord

rails docs显然是错误的 - http://guides.rubyonrails.org/association_basics.html#selfjoins

  

在设计数据模型时,您有时会找到一个应该的模型   与自己有关系。 [...]

class Employee < ActiveRecord::Base   
  has_many :subordinates, :class_name => "Employee"   
  belongs_to :manager, :class_name => "Employee",
    :foreign_key => "manager_id" 
end 
  

使用此设置,您可以检索@ employee.subordinates和   @ employee.manager。


实际上,至少在控制台中,如果foreign_key不是“employee_id”,则会在上面生成错误。

这是我的具体代码:

#Table name: plates
#
#  id         :integer         not null, primary key
#  name       :string(255)
#  datetime   :datetime
#  parent_id  :integer
#  precision  :integer
#  tags       :string(255)
#  created_at :datetime        not null
#  updated_at :datetime        not null
#

class Plate < ActiveRecord::Base

  has_many :templates

  has_many :children, :class_name => "Plate"
  belongs_to :parent, :class_name => "Plate",
    :foreign_key => "parent_id"
  [...] 

...以及我运行的查询:

irb(main):002:0> Plate.find_by_name("blog090822").children.first

如果我运行它会生成查找plate_id的SQL,然后为不存在的列返回错误。如果我通过迁移将列名更改为plate_id,请重新设置数据库并重新运行它可以运行的查询。

如果 是一个rails文档错误,那就多么普遍了。

1 个答案:

答案 0 :(得分:1)

API documents中,foreign_key有一些解释。对于belongs_to

By default this is guessed to be the name of the association with an “_id” suffix.

has_many

By default this is guessed to be the name of this class in lower-case and “_id” suffixed.

因此,在您的情况下,foreign_key for:children应为plate_id,而foreign_key for:parent应为parent_id。 要在保持数据架构的同时让代码正常工作,只需要foreign_key for:children,这会使用foreign_key覆盖默认parent_id

Rails指南中的代码可能有误。

相关问题