2017-10-10 78 views
0

假设为以下迁移:ActiveRecord的抱怨柱(供参考)不存在,所以手动创建它和它抱怨它确实存在

class AddSectionReferences < ActiveRecord::Migration 
    def change 

    add_reference :sections, :sections, index: true, foreign_key: true, on_delete: :nullify 
    add_reference :sections, :parent 
    end 
end 

它抱怨:

ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR: column "section_id" referenced in foreign key constraint does not exist 
: ALTER TABLE "sections" ADD CONSTRAINT "fk_rails_810c69e885" 

所以如果我添加:

add_column :sections, :sections_id, :integer 

参考之前再抱怨:

ActiveRecord::StatementInvalid: PG::DuplicateColumn: ERROR: column "sections_id" of relation "sections" already exists 
: ALTER TABLE "sections" ADD "sections_id" integer 

这是怎么回事,为什么它在第一个错误寻找section_id列,当我试图创建(为的has_many)复数列?

回答

1

当我试图创建一个复数列(对于has_many)?

你从错误的一端接近了这个。你如何想象这个专栏包含多个/无限ID?这不是铁轨预期的事情。

has_many关系中,外键列位于belongs_to一侧。列名自然是单数。因为它只能保存一个ID。

t.references :section 
+0

http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association OP应遵循此 – Mark

+0

@马克:你认为是这样吗? –

+0

从他的问题看起,他还没有看到它:( – Mark