我有一个包含人员表,电子邮件表,电话表和地址表的架构。
人员模型
class Person< ApplicationRecord
has_many :emails, dependent: :destroy
accepts_nested_attributes_for :emails
default_scope { order(created_at: :desc) }
end
电子邮件模型
class Email< ApplicationRecord
belongs_to :Person
has_one :phone, dependent: :destroy
has_many :address, dependent: :destroy
accepts_nested_attributes_for :phone
accepts_nested_attributes_for :address
end
手机型号
class Phone< ApplicationRecord
belongs_to :Email
end
地址模型
class Address < ApplicationRecord
belongs_to :Email
end
我的模式如下
ActiveRecord::Schema.define(version: 2019_06_03_231058) do
create_table "emails", id: :string, limit: 36, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci", force: :cascade do |t|
t.boolean "deleted", default: false, null: false
t.datetime "created_at", precision: 3, null: false
t.datetime "updated_at", precision: 3, null: false
t.string "Person_id", limit: 36
t.index ["Person_id", "created_at"], name: "index_email_on_Person_id_and_created_at"
end
create_table "phones", id: :string, limit: 36, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci", force: :cascade do |t|
t.string "phone_id", limit: 36, null: false
t.boolean "deleted", default: false, null: false
t.datetime "created_at", precision: 3, null: false
t.datetime "updated_at", precision: 3, null: false
t.string "email_id", limit: 36
t.string "person_id", limit: 36
t.index ["email_id", "created_at"], name: "index_phone_on_email_id_and_created_at"
t.index ["person_id"], name: "fk_rails_7119a1d90f"
end
create_table "persons", id: :string, limit: 36, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci", force: :cascade do |t|
t.boolean "deleted", default: false, null: false
t.datetime "created_at", precision: 3, null: false
t.datetime "updated_at", precision: 3, null: false
t.index ["created_at"], name: "index_persons_on_created_at"
end
create_table "address", id: :string, limit: 36, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci", force: :cascade do |t|
t.string "address_id", limit: 36, null: false
t.boolean "deleted", default: false, null: false
t.datetime "created_at", precision: 3, null: false
t.datetime "updated_at", precision: 3, null: false
t.string "email_id", limit: 36
t.string "person_id", limit: 36
t.index ["email_id", "created_at"], name: "index_address_on_email_id_and_created_at"
t.index ["person_id"], name: "fk_rails_485c78b376"
end
add_foreign_key "emails", "persons"
add_foreign_key "phones", "emails"
add_foreign_key "phones", "persons"
add_foreign_key "address", "emails"
add_foreign_key "address", "persons"
end
因此,如果您最后在我的架构中注意到,我有2个用于电话和地址的外键。
当我插入数据时,将email_id放在person表中,而不是person_id。 我在放置了email_id的地址表中也看到了同样的问题,但是没有person_id
我是Rails的新手,但通过在线文档无法真正解决此问题时,Active Record概念还是无济于事。