Make acts_as_versioned create new version on demand

I use acts_as_versioned to manage versions of Rails models. As I don’t want to create a new version of my document everytime I save it (to fix a typo for instance), I added a virtual attribute called save_with_revision to my model and put it into the definition of version_condition_met?.

  1. attr_accessor :save_with_revision  
  2.   
  3. def version_condition_met?  
  4.   @save_with_revision.to_s[/true|1/] != nil  
  5. end  

Cool… except that it does not save intermediate updates into the **_versions table. Let say you create document version 1.0, then update it without creating a new version (from v1.1 to v1.4) and finally save a new version (v2.0); v1 will still be v1.0 and not v1.4.

To save intermediate updates into the **_versions table, just add to your model:

  1.     
  2. def after_update  
  3.   if !version_condition_met? && changed?  
  4.     versions.find(:last).update_attributes(self.attributes)  
  5.   end  
  6. end  

Hope it helps. :)
Anyone with a better solution?

Post to Twitter

. Bookmark the permalink. Both comments and trackbacks are currently closed.
  • Hi, my name is Philippe Creux.

    This blog is about Agile project management, Ruby programming and other cool things. I haven't published anything here since 2011. Find the latest and greatest on pcreux.com!