0

I am implementing a User that is not actually deleted from the system with destroy but only marked with :active = false.

The problem here is that such an inactivate user will show up in all User.find, User.all, ... calls. I don't want to pollute the code with all kinds of 'if-else's or overwriting the behavior of .find, .all etc.

I just want to know whether I can nicely define it within the User's model so that inactive users will virtually disappear unless I explicitly want to extract such a user.

If there is no way to do it in the model then what are my options?

2 Answers2

2

Use a scope, or a class method with a where clause.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • 1
    Scopes are fine; the issue in the post was fixed. `acts_as_paranoid` is a pre-built solution if you don't already have everything set up as @socjopata said. – Dave Newton Sep 09 '11 at 13:07
  • Thank you, but it is not exactly what I wanted. As far as I read through the material 'scope' is just some kind of class function, and I will still have to type 'User.activated.find(...)'. I wanted an initial filtering of such records from the class unless I specify that I want to see them. –  Sep 09 '11 at 14:14
  • 1
    Set a default scope, and override when necessary. http://stackoverflow.com/questions/2073419/overriding-default-scope-in-rails – Dave Newton Sep 09 '11 at 14:44
  • Thanks again! Yep, it looks nice. Anyway, i have added a class method for active users. –  Sep 10 '11 at 12:32
0

I think you may want to check acts_as_paranoid Here is a link for one of the implementations: https://github.com/technoweenie/acts_as_paranoid

From the wiki:

Now whenever destroy is called on that model, it is just removed from view and the deleted_at column set to the current date time. All the finder methods ignore “deleted” records.

socjopata
  • 5,028
  • 3
  • 30
  • 33