Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Retrieve associated belongs_to record without using with_deleted for belongs_to association #502

Closed
Anas-Shahid opened this issue Dec 4, 2020 · 3 comments

Comments

@Anas-Shahid
Copy link

Anas-Shahid commented Dec 4, 2020

Hi!
First of all, thank you for this amazing gem, it has helped me ALOT.
So, I'm trying to retrieve the soft-deleted belongs_to record without using with_deleted for the belongs_to association, as it would disturb the normal flow of the associations used elsewhere in the app.
Here's what I'm trying to do:

   class Leave < ApplicationRecord
       acts_as_paranoid
       
       belongs_to :user
   end

   class User < ApplicationRecord
       acts_as_paranoid
       
       has_many :leaves, dependent: :destroy
   end

I'm trying to retrieve the deleted User, from the deleted Leave like so:

   Leave.with_deleted.find(1).user.with_deleted

Expected Behavior

Retrieve the deleted user for the deleted leave.

Actual Behavior

Getting error: `undefined method `with_deleted' for nil:NilClass`

Though, I'm able to retrieve the deleted leave.

Configuration

Ubuntu 20.04
Rails 5.1.7
Ruby 2.5.7

Please guide me on what I'm doing wrong.

Thanks 🙂

@ozzyaaron
Copy link

Just commenting here because I was looking at a similar issue.

The quick fix is something like

belongs_to :user, -> { with_deleted }

or

belongs_to :user, -> { unscope(where: :deleted_at) }

In my case I used the latter as I had a polymorphic belongs_to where not all polymorphic classes included the with_deleted scope.

That being said I think if the User is deleted you probably don't want to included deleted users in a normal association like that.

In my experience having a separate association to include deleted items will serve better in the long run.

@Anas-Shahid
Copy link
Author

@ozzyaaron - Thanks for the reply.

Yes, I agree with you to separate these associations.

@Anas-Shahid
Copy link
Author

Can be achieved by following this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants