Rails - operation outside of a rollback

Posted by Brian Armstrong on Stack Overflow See other posts from Stack Overflow or by Brian Armstrong
Published on 2010-06-06T08:16:21Z Indexed on 2010/06/06 8:22 UTC
Read the original article Hit count: 373

I have a before_create filter that checks if people are posting too many comments.

If they are I want to flag their account.

class Comment < ActiveRecord::Base
  before_create :check_rate_limit

  def check_rate_limit
    comments_in_last_minute = self.user.comments.count(:conditions => ["comments.created_at > ?", 1.minute.ago])
    if comments_in_last_minute > 2
      user.update_attribute :status, "suspended"
      return false
    end
    true
  end
end

The before filter returns false to stop the comment from being created. The problem is that this triggers a ROLLBACK which also undoes the changes I made to the user model.

What's the correct pattern to accomplish this? Specifically: running a check each time an object is created and being able to edit another model if the check fails.

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about rollback