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?
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