Rails 观察者、插件和迁移正在进行一场竞赛,谁会获胜?

发布于 2024-12-04 17:53:53 字数 239 浏览 2 评论 0原文

我们刚刚向 Rails 应用程序添加了几个观察者。现在,当从头开始运行迁移时,我们收到一条错误,指出表不存在(呃,我们还没有迁移)。抛出错误是因为正在加载模型中的插件,要求提供列名称。

我假设观察者导致模型被加载,因为当我们注释掉 application.rb 中的观察者行时,不会引发错误。

如何在不加载观察者和模型的情况下运行迁移?

或者

如何在运行迁移时以不会引发错误的方式在插件中请求列名称?

We just added a couple of observers to our Rails application. Now, when running migrations from scratch we get an error saying that a table doesn't exist (duh, we haven't migrated yet). The error is thrown because a plugin in a model is being loaded that asks for column_names.

I am assuming that the observers are causing the models to be loaded because when we comment out the observers line in application.rb, the error is not thrown.

How do I run migrations without loading observers and models?

or

How do I ask for the column_names in my plugin in a way that won't throw an error when running migrations?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

辞取 2024-12-11 17:53:53

在 Rails 3 中,您可以通过确定 Rake 是否正在运行来跳过添加观察者:

config.active_record.observers = :my_model_observer unless File.basename($0) == 'rake'

这会关闭观察者,这意味着不会加载模型和插件。

In Rails 3 you can skip adding the observers by determining if Rake is being run:

config.active_record.observers = :my_model_observer unless File.basename($0) == 'rake'

This turns off the observers, which means the models and plugins aren't loaded.

述情 2024-12-11 17:53:53

我还没有找到在运行时禁用观察者的好方法。这已经在 在 rake 期间关闭观察者的简单方法中讨论过任务?

但是,我想您可以通过在迁移中重新定义麻烦的模型来从模型中“拔出”插件代码:

class YourMigration < ActiveRecord::Migraation
  class YourModel < ActiveRecord::Base; end

  def self.up
    ...
  end

  def self.down
    ...
  end
end

I haven't found a decent way to disable Observers at run time. This has been previously discussed in Simple way of turning off observers during rake task?

However, I guess you could "unplug" the plugin code from your model by redefining the troublesome model in your migration:

class YourMigration < ActiveRecord::Migraation
  class YourModel < ActiveRecord::Base; end

  def self.up
    ...
  end

  def self.down
    ...
  end
end
要走干脆点 2024-12-11 17:53:53

在您的模型中,您可以捕获运行迁移时生成的特定异常。

In your model you can catch the specific exception generated when you run migrations.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文