在Rails迁移中定义方法 [英] Defining methods in Rails migrations

查看:80
本文介绍了在Rails迁移中定义方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在迁移过程中定义一个方法,但出现了未定义的方法错误:

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?

推荐答案

您可能会从错误消息中看到,代码不是从迁移类内部而是在连接适配器内部调用的.我不确定,但是这个小的更改应该可以工作:

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.

这篇关于在Rails迁移中定义方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆