0
我想實現一個模型Person,其中Person has one parent
和has_many children
。我也不想創建任何其他模型。無法理解由軌道提供的有效記錄自我加入聯想的方法
角色模型
class Person < ActiveRecord::Base
has_one :parent, :class_name => 'Person', :foreign_key => :parent_id
has_many :children, :class_name => 'Person', :foreign_key => :children_id, :dependent => :destroy
end
Person(id: integer, name: string, created_at: datetime, updated_at: datetime, parent_id: integer, children_id: integer)
1.9.3-p194 :024 > @a
=> #<Person id: 8, name: "a", created_at: "2015-02-10 05:53:28", updated_at: "2015-02-10 06:53:35", parent_id: nil, children_id: nil>
1.9.3-p194 :025 > @b
=> #<Person id: 11, name: "b", created_at: "2015-02-10 06:36:31", updated_at: "2015-02-10 06:57:03", parent_id: 8, children_id: 12>
1.9.3-p194 :026 > @ab
=> #<Person id: 12, name: "ab", created_at: "2015-02-10 06:54:50", updated_at: "2015-02-10 06:54:50", parent_id: nil, children_id: nil>
現在@a.parent =>
Person Load (0.3ms) SELECT "people".* FROM "people" WHERE "people"."parent_id" = $1 ORDER BY "people"."id" ASC LIMIT 1 [["parent_id", 8]]
=> #<Person id: 11, name: "b", created_at: "2015-02-10 06:36:31", updated_at: "2015-02-10 06:57:03", parent_id: 8, children_id: 12>
至於我知道@a
沒有任何parent
因爲parent_id is nil
。那麼@ a.parent如何工作。
閱讀[ActiveRecord associations](http://guides.rubyonrails.org/association_basics.html)。 – 2015-02-10 07:26:50
Ok代替 'has_one:parent,:class_name =>'Person',::foreign_key =>:parent_id',它應該是'belongs_to:parent,:class_name =>'Person''是的,現在它工作了! – VKatz 2015-02-10 07:31:39