I have three models. Customer, Address, and CreditMemo.
Originally, I had a non polymorphic model Address and I changed it to polymorphic when I created CreditMemo so they could both share the same model. Since then, when I try to create a record with a different parent type than Customer, I get a validation error saying the Customer parent doesn't exist.
Before I created CreditMemo I simply had a 1-to-many association between Customer and Address. Here is the migration I made to change Address to polymorphic.
class MakeAddressPolymorphic < ActiveRecord::Migration[5.1]
def up
rename_column :addresses, :customer_id, :addressable_id
add_column :addresses, :addressable_type, :string
add_index :addresses, [:addressable_id, :addressable_type]
Address.reset_column_information
Address.update_all(:addressable_type => "Customer")
end
def down
rename_column :addresses, :addressable_id, :customer_id
remove_column :addresses, :addressable_type
end
end
My schema after the migration:
create_table "addresses", force: :cascade do |t|
t.text "line_1"
t.text "line_2"
t.string "city"
t.string "state"
t.string "zip_code"
t.string "address_type"
t.bigint "addressable_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "same_as_billing"
t.string "addressable_type"
t.index ["addressable_id", "addressable_type"], name: "index_addresses_on_addressable_id_and_addressable_type"
t.index ["addressable_id"], name: "index_addresses_on_addressable_id"
end
I can create a customer with the nested attributes just fine. However, when I try to create a CreditMemo with the nested address atrributes, I get this error:
PG::ForeignKeyViolation: ERROR: insert or update on table "addresses" violates foreign key constraint "fk_rails_d5f9efddd3" DETAIL: Key (addressable_id)=(36) is not present in table "customers". : INSERT INTO "addresses" ("line_1", "line_2", "city", "state", "zip_code", "address_type", "addressable_id", "created_at", "updated_at", "addressable_type") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING "id"
Here is my Customer model:
has_many :addresses, :as => :addressable, inverse_of: :addressable
accepts_nested_attributes_for :addresses
My CreditMemo model:
has_many :addresses, :as => :addressable, inverse_of: :addressable
accepts_nested_attributes_for :addresses
My Address model:
belongs_to :addressable, :polymorphic => true
I'm pretty sure the issue is in this line which is at the bottom of my schema:
add_foreign_key "addresses", "customers", column: "addressable_id"
I'm not sure how to fix this or what it should be .