使用多态嵌套属性创建关联时出错

时间:2018-08-10 16:32:12

标签: ruby-on-rails ruby ruby-on-rails-5

我有三种型号。 CustomerAddressCreditMemo

最初,我有一个非多态模型Address,在创建CreditMemo时我将其更改为多态模型,因此他们可以共享同一模型。从那时起,当我尝试创建父类型不同于Customer的记录时,我收到一条验证错误,指出“客户”父项不存在。

在创建CreditMemo之前,我只是在1-to-manyCustomer之间建立了Address关联。这是我将Address更改为多态的迁移。

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

迁移后的我的架构:

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

我可以使用嵌套属性来创建客户。但是,当我尝试使用嵌套地址属性创建CreditMemo时,出现此错误:

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"

这是我的Customer模型:

has_many :addresses, :as => :addressable, inverse_of: :addressable
accepts_nested_attributes_for :addresses

我的CreditMemo模型:

has_many :addresses, :as => :addressable, inverse_of: :addressable
accepts_nested_attributes_for :addresses

我的Address模型:

belongs_to :addressable, :polymorphic => true

我很确定问题出在这行中,这是我模式的底部:

add_foreign_key "addresses", "customers", column: "addressable_id"

我不确定如何解决此问题或应解决的问题。

1 个答案:

答案 0 :(得分:1)

您不能将外键与多态关联一起使用,因此必须从架构中删除外键,为此可以使用remove_foreign_key

只需使用以下代码进行新的迁移:

remove_foreign_key :addresses, :customers