Defining methods in Rails migrations

空扰寡人 提交于 2019-12-23 07:40:18

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/1484302/defining-methods-in-rails-migrations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!