2016-07-05 10 views
0

Ein Produkt hat viele Produktbilder und Produktbild gehört zu einem Produkt. Hier ist das Schema sind, istproduct_id referenziert in Fremdschlüsseleinschränkung existiert nicht

create_table "product_images", force: :cascade do |t| 
    t.string "image" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    end 

    create_table "products", force: :cascade do |t| 
    t.string "name" 
    t.integer "price" 
    t.boolean "availability" 
    t.text  "about" 
    t.integer "ref" 
    t.string "texture" 
    t.string "dimensions" 
    t.string "shipping" 
    t.string "category" 
    t.string "notes" 
    t.datetime "created_at",    null: false 
    t.datetime "updated_at",    null: false 
    t.string "sizes",  default: [],    array: true 
    end 

Hier werden die Modelle

class ProductImage < ActiveRecord::Base 
    belongs_to :product 
end 

class Product < ActiveRecord::Base 

    has_many :product_images 

end 

ich eine Migration hinzufügen bin versucht, referenzieren product_id als Fremdschlüssel product_images Tabelle

class AddForeignKeyToProductImages < ActiveRecord::Migration 
    def change 
    add_foreign_key :product_images, :products, column: :product_id 
    end 
end 

Hier ist der Fehler

== 20160705023021 AddForeignKeyToProductImages: migrating ===================== 
-- add_foreign_key(:product_images, :products, {:column=>:product_id}) 
rake aborted! 
StandardError: An error has occurred, this and all later migrations canceled: 

PG::UndefinedColumn: ERROR: column "product_id" referenced in foreign key constraint does not exist 
: ALTER TABLE "product_images" ADD CONSTRAINT "fk_rails_1c991d3be6" 
FOREIGN KEY ("product_id") 
    REFERENCES "products" ("id") 

Antwort

2

Es sollte funktionieren:

rails g migration AddProductToProductImages 

class AddProductToProductImages < ActiveRecord::Migration 
    def change 
    add_column :product_images, :product_id, :integer 
    add_foreign_key :product_images, :products 
    end 
end 

Sie können auch Folgendes tun:

rails g migration AddProductRefToProductImages product:references 

class AddProductToProductImages < ActiveRecord::Migration 
    def change 
    add_reference :product_images, :product, index: true, foreign_key: true 
    end 
end 

Sie können die API für weitere Informationen überprüfen.

1

Löschen Sie die Migrationsdatei "AddForeignKeyToProductImages". Dann ...

Führen Sie diesen Befehl in der Konsole:

rails g migration AddProductToProductImages product:references 

Welche der folgenden Migration erzeugen sollte.

class AddProductToProductImages < ActiveRecord::Migration 
    def change 
    add_reference :product_images, :product, index: true 
    end 
end 

Führen Dann bundle exec rake db:migrate

Verwandte Themen