2012-03-25 19 views
1

軌道文檔顯然是錯誤的 - http://guides.rubyonrails.org/association_basics.html#selfjoinsMany-One Self Join - rails擁有文檔錯誤?

在設計數據模型,你會發現,有時一個模型應該 有一個關係到自身。 [...]

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 

如果我運行它生成SQL尋找plate_id,然後返回一個錯誤的非存在的列。如果我通過遷移將列名更改爲plate_id,請重新設置數據庫並重新運行查詢。

如果這個一個rails文檔錯誤,這是多麼平常。

回答

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爲:兒童應plate_idforeign_key爲:父母應該parent_id。 爲了讓您的代碼在保持數據模式的同時工作,只需要foreign_key for:children,這會覆蓋默認的foreign_keyparent_id

Rails指南中的代碼可能是錯誤的。