无法理解由rails提供的活动记录自加入关联的方法

时间:2015-02-10 07:22:38

标签: ruby-on-rails ruby-on-rails-4 associations

我想在Person has one parenthas_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如何运作。

1 个答案:

答案 0 :(得分:1)

问题是你使用了两个外键parent_idchildren_id,所以即使你从一侧销毁链接,另一方仍然知道那个孩子/父母仍然存在,通过另一个外键,基本的一对多关系转换为在许多记录中的id上有id,所以你只需要在子记录中parent_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外键