【问题标题】:How to get all children given a parent id?如何让所有孩子都有一个父母ID?
【发布时间】:2018-02-20 02:28:28
【问题描述】:

我有一个名为“Person”的模型,它有“mother”和“father”字段(一对一的关系指向同一个类),所以现在我想获取一个人的所有孩子 我该怎么做?

这是模型

class Person < ApplicationRecord
  has_many :mails, dependent: :destroy
  has_many :phones, dependent: :destroy

  has_one :spouse, class_name: 'Person'
  has_one :father, class_name: 'Person'
  has_one :mother, class_name: 'Person'
end

这就是迁移

class CreatePeople < ActiveRecord::Migration[5.1]
  def change
    create_table :people do |t|
      t.string :rut, unique: true
      t.string :dv
      t.string :names
      t.string :paternal_surname
      t.string :maternal_surname
      t.date :birth_date
      t.date :death_date
      t.string :civil_status
      t.string :sex
      t.string :nationality

      t.references :father
      t.references :mother
      t.references :spouse

      t.timestamps
    end
  end
end

我想通过以下方式访问孩子:

Person.children

但我是 RoR 的新手,我不知道该怎么做。

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    您需要指定一个 Person 有很多孩子。类似于您所说的 Person 有很多邮件和电话。

    从那里,调整你的代码,说一个人属于一个父亲,而不是有一个。

    class Person < ApplicationRecord
      has_many :mails, dependent: :destroy
      has_many :phones, dependent: :destroy
      has_many :children, class_name: 'Person'
    
      has_one :spouse, class_name: 'Person'
      belongs_to :father, class_name: 'Person'
      belongs_to :mother, class_name: 'Person'
    end
    

    【讨论】:

    • belongs_to 的问题是我无法插入没有父亲或母亲的记录。这就是为什么我使用has_one 更新:我在belongs_to 中使用optional: true,但是当我调用Person.children 时它给了我这个错误:NameError (uninitialized constant Person::Child)
    • 我认为这是我的错误,尝试将 Person 的类名添加到 has_many children 行。
    猜你喜欢
    • 1970-01-01
    • 2015-03-26
    • 1970-01-01
    • 1970-01-01
    • 2018-04-19
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    相关资源
    最近更新 更多