Ruby on rails 自定义验证到位时保存记录时出错
我有一个API,可以保存视频、索引和更新它们。为了减少编制索引的时间,我决定只对已更改或新的索引视频添加一些验证。在此之前:Ruby on rails 自定义验证到位时保存记录时出错,ruby-on-rails,ruby,activerecord,attr-accessor,Ruby On Rails,Ruby,Activerecord,Attr Accessor,我有一个API,可以保存视频、索引和更新它们。为了减少编制索引的时间,我决定只对已更改或新的索引视频添加一些验证。在此之前: class Video < ActiveRecord::Base after_save :index_me def index_me Resque.enqueue(IndexVideo, self.id) end end class-Video
class Video < ActiveRecord::Base
after_save :index_me
def index_me
Resque.enqueue(IndexVideo, self.id)
end
end
class-Video
我所作的改动如下:
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
class-Video
没有这些改变,一切都很好,只是每个视频都会被索引,即使没有任何改变。但根据我的更改,当视频试图保存到数据库时,它会回滚。有什么想法吗?首先,你可以摆脱在保存后检测记录是否为新记录的黑客行为。如果记录是新的,那么.更改了吗?方法将返回true
class Video < ActiveRecord::Base
after_save :index_me
def index_me
Resque.enqueue(IndexVideo, self.id) if self.changed?
end
end
class-Video
如果我没有错,当回调之前的返回false
时,事务将回滚。
这可能就是正在发生的事情
def check_new_record
self.is_new = self.new_record?
end
当self.new\u记录?
返回false
时,它将false
赋值给self.is\u new
,然后该方法返回self.is\u new
,这也是false
请尝试以下方法:
def check_new_record
self.is_new = self.new_record?
true
end
你能在控制台上创建一个新的视频,保存它,并向我们显示日志输出(包括日志中的SQL)吗?我们能看到IndexVideo类吗?IndexVideo向索引服务器发送HTTP post,与数据库没有交互,所以我认为它不相关。我测试了并保存了记录。更改了吗?这是一个错误,请检查前面回答的问题:看起来是这样的。