Written by Sean Behan on Sun Jun 17th 2012

Versioning models with the acts_as_versioned plugin

cd rails/app
./script/plugin install git://github.com/technoweenie/acts_as_versioned.git
./script/generate model post title:string body:text

In your model

class Post < ActiveRecord::Base
  acts_as_versioned
end

In db/migrate/****_create_posts.rb

  def self.up
    create_table :posts do |t|
      t.string :title
      t.text :body
      t.timestamps
    end
    Post.create_versioned_table
  end

def self.down drop_table :posts Post.drop_versioned_table end

Migrate your db
rake db:migrate
Usage
p = Post.create :body => "hello world"
p.body = "HELLO WORLD"
p.save

p.versions.size p.versions.last p.revert_to(p.versions.first) p.body # => hello world

*Quick Note If you want to revert to an older version in a controller or something, don't do

@post = @post.revert_to(2)
Revert_to method will return a TrueClass, Boolean type. Instead use
@post.revert_to(2)
This method will update the attributes for you and when you call them you'll get that version.

More information is available here http://ar-versioned.rubyforge.org/ and http://www.urbanhonking.com/ideasfordozens/archives/2006/02/learns_to_use_a_1.html


Tagged with..
#active record #plugins #Ruby on Rails

Just finishing up brewing up some fresh ground comments...