Domien
Domien

Reputation: 405

Ruby on rails: dependent destroy not working with renamed foreign key

I didn't find any related threads on this, so I made a new question myself. I have following models. I added foreign_key: :sender in the class User because the field name :sender of the model class Comment differs from the model class User. I added dependent: :destroy to the class User to make sure when an user is deleted all of its comments are deleted as well. However when I destroy an user, their comments do not get destroyed. The comments remain in the database. I don't see why.

class Comment < ApplicationRecord
  belongs_to :sender, :class_name => "User"
  belongs_to :event
end

class User < ApplicationRecord     
  has_many :comments, dependent: :destroy, foreign_key: :sender
end

class CommentsController < ApplicationController
<snip>
def destroy
    @event = Event.find(params[:event_id]) # dont mind this line
    @comment = Comment.find(params[:id])
    @comment.destroy
    redirect_to event_path(@event) # dont mind this either
  end
<snip>
end

class UsersController < ApplicationController
<snip>
def destroy
    @user = User.find(params[:id])
    @user.destroy

    redirect_to users_path
  end
<snip>
end

Upvotes: 2

Views: 1290

Answers (1)

Domien
Domien

Reputation: 405

I managed to fix it by changing foreign_key: :sender to foreign_key: :sender_id. In other words, the real db column :sender_id has to be given instead of the field name :sender.

However, when I was using foreign_key: :sender before I did not get any errors from rails. It just did not the delete the comments when deleting an user. If anyone can explain why I did not see any errors, I would like to hear from you.

Upvotes: 2

Related Questions