2017-10-10 83 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