Skip to content

Easy « paranoid » with Rails 3 and state_machine

25/08/2010

Do you remember the good old « acts_as_paranoid » plugin for Rails? The bahaviour of the plugin is simple : you want to « soft »-delete the records in your database.

When your users use your app to destroy a record, they don’t see it anymore, but the record is still kept in the database for security purposes.

Since the latest versions of Rails 2 it’s been very easy to implement this kind of behaviour using default_scope. With Rails 3, the state_machine gem and the « unscoped » method the syntax is even nicer!

class Post < ActiveRecord::Base
  state_machine :state, :initial => :published do
    event :delete do
      transition all => :deleted
    end
  end
  
  default_scope without_state(:deleted)
end
  post = Post.find(1)  # => load Post with ID=1
  post.delete  # => post is now soft-deleted!

  Post.find(1)  # => ActiveRecord::RecordNotFound

  Post.unscoped.find(1)  # => really load it if we want
  Post.unscoped do
    # do your stuff WITH all Post records... for example in your admin area.
  end
Publicités

From → rails, ruby

5 commentaires
  1. rds permalink

    #delete is already an instance method defined on AR… An archive state would be a better bet.

  2. I thought #delete was only a class method, but you’re right rds, it’s also an instance method.
    So like you said, an other state/event name would be better.

  3. Weren’t there problems with other soft-delete progams where things like associations didn’t honour the default scope.

  4. Good question. I know there were some problems with default_scoping on Rails 2, don’t know if all these problems have been fixed on Rails 3.

    I’ll update this blog post if I find any.

Laisser un commentaire

Entrez vos coordonnées ci-dessous ou cliquez sur une icône pour vous connecter:

Logo WordPress.com

Vous commentez à l'aide de votre compte WordPress.com. Déconnexion / Changer )

Image Twitter

Vous commentez à l'aide de votre compte Twitter. Déconnexion / Changer )

Photo Facebook

Vous commentez à l'aide de votre compte Facebook. Déconnexion / Changer )

Photo Google+

Vous commentez à l'aide de votre compte Google+. Déconnexion / Changer )

Connexion à %s

%d blogueurs aiment cette page :