user1099385
user1099385

Reputation:

Rails 3 vestal_versions: Create new version at parent model upon change in child model

using Rails 3 with the vestal_versions gem and have this situation:

class Post < ActiveRecord::Base
  versioned
  has_many :comments
  (...)
end

class Comment < ActiveRecord::Base
  belongs_to :post
  (...)
end

Versioning of the Post model works flawlessly. What I want is, that as soon as the associated Comment model gets created/updated, the related Post model should get a new version. (I do not have the need for the restoration feature of vestal_versions.)

What would be the right strategy to accomplish this?

Upvotes: 1

Views: 169

Answers (1)

rmagnum2002
rmagnum2002

Reputation: 11421

I used papertrail gem for this type of tasks, but this should work the same for you. An idea would be to update the post of the comment, when comment will be created - save will be called on it's post and will create a new version of this post. Something like this:

class Comment < ActiveRecord::Base
  belongs_to :post
  after_create :update_post

  def update_post
    self.post.save
  end
end

again, probably not the best way as you have to call save on post each time you add a comment and this is a performance issue.

update based on kwirschau comment

  def update_post
    self.post.send(:create_version)
  end

Upvotes: 0

Related Questions