我想在Person has one parent
和has_many children
中实现一个模型Person。我也不想创建任何其他模型。
人物模型
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如何运作。
答案 0 :(得分:1)
问题是你使用了两个外键parent_id
和children_id
,所以即使你从一侧销毁链接,另一方仍然知道那个孩子/父母仍然存在,通过另一个外键,基本的一对多关系转换为在许多记录中的id上有id,所以你只需要在子记录中parent_id
以下是您需要在模型中更改的内容:
class Person < ActiveRecord::Base
belongs_to :parent, class_name: 'Person', foreign_key: :parent_id
has_many :children, class_name: 'Person', foreign_key: :parent_id, dependent: :destroy
end
注意我将has_one
替换为belongs_to
,因为子项具有父项的ID,而不是相反,并且都使用相同的parent_id
外键