【问题标题】:Rails ActiveRecord. how can I deal with belong_to more than one?Rails 活动记录。我如何处理多个belong_to?
【发布时间】: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 仍然有效吗?

【问题讨论】:

标签: ruby-on-rails activerecord belongs-to


【解决方案1】:

不,如果你有多个父母可以有多个孩子,belongs_to 不合适。

你想要 has_many through:... 它将使用一个连接表...你可以随意调用它,但 relationships 似乎合适。

另外,将您的 People 类更改为 Person 类以遵循 Rails 约定。

class Person < ActiveRecord::Base

  has_many :ancestors, class_name: 'Relationship', foreign_key: :child_id
  has_many :descendants, class_name: 'Relationship', foreign_key: :parent_id
  has_many :parents, through: :ancestors, class_name: 'Person', foreign_key: :parent_id
  has_many :children, through: :descendants, class_name: 'Person', foreign_key: :child_id

end

如果需要,您可以在“关系”表中存储其他信息,例如“母亲”或“父亲”和“儿子”或“女儿”……尽管如果这样的话,从 Person 的性别推断可能会更好存在。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-11
    • 2021-07-12
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多