如何在加载灯具之后但在创建保存点之前执行SQL语句?

时间:2011-01-16 15:57:44

标签: mysql ruby-on-rails auto-increment

我们有一个模型,它使用另一个模型表上的auto_increment从另一个模型的ID中获取序列号。每当重新启动数据库服务器时,该值都将设置为零,因此序列号将重置。要解决这个问题,在after_initialize块中,我们将auto_increment值设置为最大序列值加1,一切都很好。

然而,在测试中,块在加载灯具之前运行,因此最大值返回为零。然后,当测试运行时,该值太低,因此测试失败。

一种可能的解决方案是更新设置块中的值,但更改表会提交当前事务,因此测试结束时的回滚失败。

如何在加载灯具后更改AUTO_INCREMENT值,但在创建保存点之前

1 个答案:

答案 0 :(得分:0)

最后找到了一种方法,通过在test_helper.rb末尾修补load_fixtures来实现此目的:

module ActiveRecord
  module TestFixtures
    def load_fixtures_with_auto_increment_reset
      load_fixtures_without_auto_increment_reset
      # code to reset auto_increment goes here
    end

    alias_method :load_fixtures_without_auto_increment_reset, :load_fixtures
    alias_method :load_fixtures, :load_fixtures_with_auto_increment_reset
  end
end