Reputation: 13289
My destroy action is throwing this error:
Failure/Error: Deal.delete(params[:id])
ActiveRecord::InvalidForeignKey:
PG::ForeignKeyViolation: ERROR: update or delete on table "deals" violates foreign key constraint "fk_rails_cc6e075aca" on table "origin_airports"
The action:
def destroy
Deal.delete(params[:id])
redirect_to deals_path
end
I've found answers about this (such as this one) and adjusted my Deal
class thusly:
has_many :origin_airports, dependent: :destroy
has_many :origins, through: :origin_airports, source: :airport
But I still get the same error.
PS. The designated answer for the post referenced above says "Yet better option to respect data integrity is to set the CASCADE DELETE on the database level." I'd love to know how to do that.
Thanks all.
Upvotes: 0
Views: 73
Reputation: 724
You can set the :dependent
option to:
:destroy
when the object is destroyed, #destroy will be called on its associated objects.
:delete
when the object is destroyed, all its associated objects will be deleted directly from the database without calling their #destroy method.
As per your settings, you have to do deal.destroy
and not deal.delete
.
You can also try (migration):
def change
remove_foreign_key "model1", "model2"
add_foreign_key "model1", "mnodel2", on_delete: :cascade
end
No data is lost since they are only indexes.
Upvotes: 1
Reputation: 32758
You should retrieve the object and then call destroy
on it instead of using the class method of delete(id)
So try this:
deal = Deal.find(params[:id])
deal.destroy
Upvotes: 1