我有一个名为section的自连接模型:
class Section < ApplicationRecord
belongs_to :offer
# Self joins:
has_many :child_sections, class_name: "Section", foreign_key: "parent_section_id"
belongs_to :parent_section, class_name: "Section", optional: true
end使用迁移文件:
class CreateSections < ActiveRecord::Migration[5.0]
def change
create_table :sections do |t|
t.string :name
t.references :offer, foreign_key: true
t.references :parent_section, foreign_key: true
t.timestamps
end
end
end使用mySql很好,但后来我删除了数据库,将它们更改为postresql (这样它们对heroku友好),并创建了新的数据库。在尝试rails db:migrate之后,出现一个错误消息:
StandardError: An error has occurred, this and all later migrations canceled:
PG::UndefinedTable: ERROR: relation "parent_sections" does not exist可能发生了什么?mysql和postgresql中的自连接有什么区别吗?
发布于 2016-09-19 06:14:32
您的t.references调用:
t.references :parent_section, foreign_key: true我将尝试用PostgreSQL做两件事:
parent_section_id.parent_section_id引用部分中的值存在)。您的问题与2有关。对于t.references :parent_section,FK将如下所示:
parent_section_id integer references parent_sections(id)因为它使用标准的Rails命名约定,所以这就是parent_sections错误的来源。您可以为FK约束指定目标表,就像向belongs_to提供:class_name一样
t.references :parent_section, :foreign_key => { :to_table => :sections }这个修复会触发您的下一个问题:您无法为不存在的表创建FK,并且在create_table :sections块执行完毕之前,sections将不会存在。
有两种常见的解决方案来解决这个问题:
create_table :sections do |t| t.string :name t.references :offer,foreign_key: true t.references :parent_section t.timestamps end add_foreign_key :sections,:sections,:column =>没有引用列(parent_section_id)的表,然后在后面添加引用列和FK。在您的迁移中类似于以下内容:
create_table :sections do |t| t.string :name t.references :offer,foreign_key: true t.timestamps end change_table :sections do |t| t.references :parent_section,:foreign_key => { :to_table => :sections } end
https://stackoverflow.com/questions/39562919
复制相似问题