Search code examples
ruby-on-railsruby-on-rails-4mongoidhas-and-belongs-to-manysoft-delete

Why there is no easy way to unscope associations in rails (mongoid)?


I tried to google and read about it, but I could not find an easy solution or a very good answer in regard to this topic. There are many similar questions, solving people's problems. I could not figure out how to solve mine and on top of that I still wonder why nobody did not solve that yet. It is such a common problem I think.


I am using Rails 4 and Mongoid 4 with Mongoid Paranoia. I want to implement a soft deletion for User. That works.

However I have an Event model which has_and_belongs_to_many :users, inverse_of: nil.

When I soft delete a user, who is a user of the event, then I seem to fail to find a way to have this user being fetched by default. Soft deleted users are not fetched, because of the default scope on User with deleted_at: nil.

Anyone enlightening out there ?

How to get started to implement something similar to what ActiveRecord offers:

has_and_belongs_to_many :users, -> { *a defined scope* }

Solution

  • I'm not sure if I am understanding you completely, but shouldn't calling another scope that utilizes unscoped do what you need. Docs here.

    default_scope { where(deleted_at: nil) }
    
    scope :some_other_scope, -> { unscoped.where(something_else: true) }
    

    Edit

    Ah, I see. Not the most elegant way but if you're set on not changing the default_scope of the User model; perhaps:

    # Event model
    def all_users
        User.unscoped.where(event: self)
    end