← Back to Upcase

Delete a model without deleting its has_many associations


(Mike Munroe) #1

I have a user model and a team member model.

user.rb (most code below stripped except for important part)

has_many :team_members, :dependent => :restrict_with_exception

team_member.rb (most code below stripped except for important part)

belongs_to :user

I want to delete a user, but not remove the team members that belong to the user. What is the best way to do this?

It seems like the only :dependent option I could use in :nullify, but that doesn’t feel right to me.


(Ben Orenstein) #2

Can’t you just remove the :dependent option entirely? Then Rails will leave the team members around.


(Mike Munroe) #3

Yes, that should work. I probably should have closed out the question or updated. The underlying problem is that I am calling a method in a before_action that is using a policy defined by Pundit within our app that is trying to match the user against the team that the user was just removed from. Moving in the right direction on that though.

Thanks!