首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails - self与postgresql连接

Rails - self与postgresql连接
EN

Stack Overflow用户
提问于 2016-09-19 05:36:21
回答 1查看 500关注 0票数 2

我有一个名为section的自连接模型:

代码语言:javascript
复制
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

使用迁移文件:

代码语言:javascript
复制
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之后,出现一个错误消息:

代码语言:javascript
复制
StandardError: An error has occurred, this and all later migrations canceled:

PG::UndefinedTable: ERROR:  relation "parent_sections" does not exist

可能发生了什么?mysql和postgresql中的自连接有什么区别吗?

EN

回答 1

Stack Overflow用户

发布于 2016-09-19 06:14:32

您的t.references调用:

代码语言:javascript
复制
t.references :parent_section, foreign_key: true

我将尝试用PostgreSQL做两件事:

  1. 在数据库中添加一个名为parent_section_id.
  2. Add a foreign key constraint的整数列,以确保引用完整性(即确保parent_section_id引用部分中的值存在)。

您的问题与2有关。对于t.references :parent_section,FK将如下所示:

代码语言:javascript
复制
parent_section_id integer references parent_sections(id)

因为它使用标准的Rails命名约定,所以这就是parent_sections错误的来源。您可以为FK约束指定目标表,就像向belongs_to提供:class_name一样

代码语言:javascript
复制
t.references :parent_section, :foreign_key => { :to_table => :sections }

这个修复会触发您的下一个问题:您无法为不存在的表创建FK,并且在create_table :sections块执行完毕之前,sections将不会存在。

有两种常见的解决方案来解决这个问题:

  1. 创建包含所有列的表,然后添加FK约束。在您的迁移中类似于以下内容:

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

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39562919

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档