Simple versioning for Rails Active Record with relationship support.
Add this line to your application's Gemfile:
gem 'versionable'And then execute:
$ bundleOr install it yourself as:
$ gem install versionableVersionable needs versions table, which can be generated using these commands:
rails g versionable:install
rails db:migrateTo enable change tracking in your model, just call acts_as_versionable. It accepts
same options as as_json method.
These options will be used to produce JSON snapshot of your data and compare it
with previous versions to detect changes.
class BlogPost < ApplicationRecord
acts_as_versionable only: [:title, :contents]
endPlease be aware that Versionable applies some changes on your configuration:
:rootwill be always set tofalse,:created_atand:updated_atwill be always excluded (that applies to included relationships as well),- Foreign keys of relationships that are listed in
includeoption will be excluded.
Versionable allows you to include related records in version snapshot. Just add
your relationships to include option:
class BlogPost < ApplicationRecord
acts_as_versionable include: :comments
has_many :comments
endAnd then define parent option on the other side of the relationship:
class Comment < ApplicationRecord
acts_as_versionable parent: :blog_post
belongs_to :blog_post
endNow even if you call store_versions on a comment, it will create version for
its blog post.
Now each time you'd like to store a version, all you have to do is to call
store_versions on your model. It takes only one optional argument wich is
version author.
class BlogPostsController < ApplicationController
def update
@blog_post = BlogPost.find(params[:id])
if @blog_post.update_attributes(blog_post_params)
@blog_post.store_versions(current_user)
# render success
else
# render failure
end
end
endContribution directions go here.
The gem is available as open source under the terms of the MIT License.