2012-03-25 9 views
1

レールのドキュメントがエラーで明らかにされている - データモデルを設計する際にMany-One Self Join - 自分のドキュメントが間違っていますか?

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」でない場合、実際には、少なくともコンソールで、エラーが上記で生成されます。

ここに私の固有のコードです:私はそれがplate_idを探してSQLを生成し、非のためのエラーを返すことを実行する場合

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

#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" 
    [...] 

...と私は実行したクエリ存在する列。マイグレーションによって列名をplate_idに変更した場合は、DBを再シードして動作するクエリを再実行します。

このの場合は、レールのドキュメントのエラーですが、どれほど一般的ですか。

答えて

1

API documentsには、foreign_keyにいくつかの説明があります。 belongs_toについて:

has_manyについては
By default this is guessed to be the name of the association with an “_id” suffix. 

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

だからあなたの場合には、用foreign_key:子供たちはplate_idであるべき、とのためforeign_key:親はparent_idでなければなりません。 データスキーマを維持しながらコードを動作させるには、children:foreign_keyのみが必要です。これはデフォルトのforeign_keyparent_idに置き換えます。

Railsガイドのコードが間違っている可能性があります。

関連する問題