ruby-on-railsrubypermissionsacts-as-paranoid

Make acts_as_paranoid finders exclude "deleted" objects conditionally


Normally, with acts_as_paranoid, when you use a finder such as find or where, it excludes entries that have a deleted_at (or whatever you named your delete column) value other than null. However, I have created a user permission that allows users to view and manipulate even "deleted" (see: hidden) entities in the database. Thing is, as it stands, I will need to check for the permission every time I want to run find, or where, or what-have-you, and if you have that permission use with_deleted as opposed to having one place that checks to see if the acts_as_paranoid logic should even work to begin with, and always adding with_deleted when that logic shouldn't.

Is there any way to accomplish this, or something similar to it, to make it all DRY?


Solution

  • You can use cancan. This allows you to define abilities. You can then define:

    if user.admin?
      can :manage, User.with_deleted
    else
      can :manage, User
    end
    

    Then you can select in the controller, using:

    User.accessible_by(current_ability)