Mirror318
Mirror318

Reputation: 12663

How can I have foreign keys that point to deleted records?

I have a Song model and an Audit model.

When I destory a Song, I want to create an Audit e.g.

if @song.destroy
  Audit.create(song: @song, deleted: true)

But this causes a crash like this:

ActiveRecord::InvalidForeignKey (PG::ForeignKeyViolation: ERROR:  insert or update on table "audits" violates foreign key constraint "fk_rails_cdcc9ea3cc"
DETAIL:  Key (song_id)=(305) is not present in table "songs".

How can I get it to happily save with an id that points to a song that no longer exists?

Upvotes: 0

Views: 442

Answers (2)

widjajayd
widjajayd

Reputation: 6253

how about using callback before_destroy to save create audit

open app/models/Song.rb

# add callback
before_destroy :audit_song

# create method
def audit_song
  Audit.create(song: self, deleted: true)
end

Upvotes: 0

allknowingfrog
allknowingfrog

Reputation: 263

Foreign keys are intended to prevent exactly this scenario. Maybe you could implement soft deletion with a Gem like acts_as_paranoid? When you soft delete something, you use a column to mark it as deleted and exclude it from queries without actually removing it from you database. That would allow you to continue accessing the Song record from your Audit model, while keeping it hidden from users.

Upvotes: 1

Related Questions