Paranoia with belongs_to

925 Views Asked by At

In my application a user has_many :jobs and a job belongs_to :user. I'm using the paranoia gem to soft delete users and jobs.

Lets say I have a user, Joe, and he has a job "Push changes". I can see all the jobs on my listing page by using Job.all, but as soon as I delete Joes' account I can't see the job using Job.all anymore.

I have tried to use Job.with_deleted.all and also tried to unscope the association belongs_to :user, -> { with_deleted }.

The SQL statement produced:

SELECT "jobs".* FROM "jobs" INNER JOIN "users" ON "users"."id" = "jobs"."user_id" AND "users"."deleted_at" IS NULL WHERE "jobs"."deleted_at" IS NULL ORDER BY users.name ASC
3

There are 3 best solutions below

0
xploshioOn On

This seems like you have set dependent: :destroy on the has many jobs, that's the only way where deleting a user, will make changes on the has_many. of you don't want them to be hided to, then just remove the dependent: :destroy from the user model on the has many jobs

0
Md. Farhan Memon On

Paranoia gem sets a default scope to your model where deleted_at attr set with timestamps are not returned. Try unscoping your model like

User.unscoped.all

0
Jinwen Zhang On

I know maybe it's too late to answer this question, but from my experience. Adding include Mongoid::Paranoia to the Job model will add deleted_at to associations instead of really deleting job records. Also, if you want to query the deleted jobs, try using Job.unscoped.all, or if want to get the deleted User from job instance, try adding a method

def user
  User.find(user_id)
end

Replace the user_id with your actual key name which maps to User id.

Hope it helps! :)