【发布时间】:2016-12-08 19:15:40
【问题描述】:
如何定义 Person 模型,以便将任何 Person 指定为另一个 Person 的父级(如下面的 Rails 控制台所示)?在为 Person 创建表的迁移过程中,您需要定义哪些列?
irb(main):001:0> john = Person.create(name: "John")
irb(main):002:0> jim = Person.create(name: "Jim", parent: john)
irb(main):003:0> bob = Person.create(name: "Bob", parent: john)
irb(main):004:0> john.children.map(&:name)
=> ["Jim", "Bob"]
我不明白答案是什么
class People < ActiveRecord::Base
has_many :children, class_name: "People", foreign_key: "parent_id"
belongs_to :parent, class_name: "People" #Question HERE? how to deal with belong_to more than one?
end
class AddXXTOXXX <ActiveRecord::Migration
def change
create_table :peoples do |t|
t.add_column :name, string
t.add_column :parent, string
t.references :parent, index: true
t.timestamps
end
end
end
但让我感到困惑的是,每个人都有两个父母(妈妈和爸爸),所以在这种情况下,belongs_to 仍然有效吗?
【问题讨论】:
-
我认为这个链接应该可以帮助你heurionconsulting.wordpress.com/2007/05/29/…
标签: ruby-on-rails activerecord belongs-to