定义 Rails 迁移中的方法

发布于 2024-08-06 03:45:42 字数 532 浏览 0 评论 0原文

我试图在迁移中定义一个方法,但出现未定义的方法错误:

undefined method 'do_something_specific' for #<ActiveRecord::ConnectionAdapters::SQLite3Adapter:0x4868018>

我不想在其他地方定义它,因为它与应用程序的其余部分并不真正相关,只是与此特定迁移相关。

需要明确的是,我的迁移看起来像:

class DoSomethingSpectacular < ActiveRecord::Migration

  def self.up
    do_something_specific(1, 2)
  end

  def self.down
  end

private

  def do_something_specific(p_1, p_2)
    # something happens here...
  end

end

我在这里错过了什么吗?为什么我不能这样定义它?

I'm trying to define a method inside a migration, but I'm getting an undefined method error:

undefined method 'do_something_specific' for #<ActiveRecord::ConnectionAdapters::SQLite3Adapter:0x4868018>

I'd rather not define it elsewhere, because it doesn't really relate to the rest of the application, just this specific migration.

To be clear, my migration looks something like:

class DoSomethingSpectacular < ActiveRecord::Migration

  def self.up
    do_something_specific(1, 2)
  end

  def self.down
  end

private

  def do_something_specific(p_1, p_2)
    # something happens here...
  end

end

Am I missing something here? Why can't I define this like this?

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

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

发布评论

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

评论(1

柏林苍穹下 2024-08-13 03:45:42

正如您从错误消息中看到的那样,代码不是从迁移类内部调用的,而是在连接适配器内部调用的。我不确定,但这个小更改应该有效:

class DoSomethingSpectacular < ActiveRecord::Migration

  def self.up
    DoSomethingSpectacular.do_something_specific(1, 2)
  end

  def self.down
  end

private

  def self.do_something_specific(p_1, p_2)
    # something happens here...
  end

end

请注意,我将您的方法设为静态并以静态方式调用它。这应该可以克服任何类范围问题。

As you may see from the error message the code isn't called from within your migration class but inside the connection adapter. I'm not sure, but this small change should work:

class DoSomethingSpectacular < ActiveRecord::Migration

  def self.up
    DoSomethingSpectacular.do_something_specific(1, 2)
  end

  def self.down
  end

private

  def self.do_something_specific(p_1, p_2)
    # something happens here...
  end

end

Note that I made your method static and called it in a static way. This should overcome any class scope issues.

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