ddonche
ddonche

Reputation: 1065

Rails polymorphic association error on user destroy

I'm trying to link notifications to users like so.

  belongs_to :notified_by, class_name: 'User'

My user has_many notifications.

  has_many :notifications, dependent: :delete_all

The problem is, when I try to destroy a user, I get an error when it goes to delete all the notifications.

ActiveRecord::StatementInvalid (PG::UndefinedColumn: ERROR:  column notifications.user_id does not exist)
LINE 1: DELETE FROM "notifications" WHERE "notifications"."user_id" ...

There is no user_id in the Notifications table, just a notified_by_id. I have tried using that in place of notified_by, but that didn't work either.

Upvotes: 0

Views: 55

Answers (1)

ddonche
ddonche

Reputation: 1065

I had to set the foreign key in the User model to recognize notified_by_id as the column to look for.

  has_many :notifications, foreign_key: 'notified_by_id', dependent: :delete_all

Upvotes: 1

Related Questions