Question

I have this API that saves videos, indexes them and updates them. In order to reduce the times the indexing was happening I decided to add some validation to only index videos that had changed or that where new. Before it was like so:

class Video < ActiveRecord::Base

  after_save :index_me

  def index_me
    Resque.enqueue(IndexVideo, self.id)
  end

end

The changes I made are as follows:

class Video < ActiveRecord::Base

  before_save :check_new_record
  after_save :index_me

  def check_new_record
    self.is_new = self.new_record?
  end

  def index_me
    if self.changed? || self.is_new
      Resque.enqueue(IndexVideo, self.id)
    end
  end

end

Without the changes everything's fine with the exception that every video gets indexed even if nothing changed. But with my changes, when a video tries to save to the database it rolls back. Any thoughts?

Was it helpful?

Solution

If I'm not wrong, when a before callback returns false, the transaction gets rolled back. That's probably what's happening.

def check_new_record
    self.is_new = self.new_record?
end

When self.new_record? returns false, it assigns false to self.is_new and then the method returns self.is_new, which is false too.

Try this instead:

def check_new_record
    self.is_new = self.new_record?
    true
end

OTHER TIPS

For one thing, you can get rid of the hack you have to detect if the record is new in the after_save. If the record is new, the .changed? method will return true.

class Video < ActiveRecord::Base
  after_save :index_me

  def index_me
    Resque.enqueue(IndexVideo, self.id) if self.changed?
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top