Rails在迁移之间共享代码(也称为关注点)

Ars*_*sen 4 ruby activerecord raise

我在相同的助手中进行了一些迁移

  private

  def add_earthdistance_index table_name, options = {}
    execute "CREATE INDEX %s_earthdistance_ix ON %s USING gist (ll_to_earth(%s, %s));" %
      [table_name, table_name, 'latitude', 'longitude']
  end

  def remove_earthdistance_index table_name
    execute "DROP INDEX %s_earthdistance_ix;" % [table_name]
  end
Run Code Online (Sandbox Code Playgroud)

而且我试图避免每次都将它们粘贴粘贴。有什么方法可以在迁移之间共享代码而无需猴子修补基类?我想找到类似concerns模型的东西。

Ars*_*sen 5

添加config.autoload_paths += Dir["#{config.root}/db/migrate/concerns/**/"]config/application.rb

在其中创建db/migrate/concerns/earthdistanceable.rb文件

module Earthdistanceable
  extend ActiveSupport::Concern

  def add_earthdistance_index table_name, options = {}
    execute "CREATE INDEX %s_earthdistance_ix ON %s USING gist (ll_to_earth(%s, %s));" %
      [table_name, table_name, 'latitude', 'longitude']
  end

  def remove_earthdistance_index table_name
    execute "DROP INDEX %s_earthdistance_ix;" % [table_name]
  end

end
Run Code Online (Sandbox Code Playgroud)

用它:

class CreateRequests < ActiveRecord::Migration[5.0]
  include Earthdistanceable

  def up
    ...
    add_earthdistance_index :requests
  end

  def down
    remove_earthdistance_index :requests

    drop_table :requests
  end

end
Run Code Online (Sandbox Code Playgroud)


fab*_*tag 4

我认为你可以这样做:

# lib/helper.rb
module Helper
  def always_used_on_migrations
    'this helps' 
  end
end
Run Code Online (Sandbox Code Playgroud)

移民

include Helper
class DoStuff < ActiveRecord::Migration
  def self.up
    p always_used_on_migrations
  end

  def self.down
    p always_used_on_migrations
  end
end
Run Code Online (Sandbox Code Playgroud)

  • @Arsen:你_知道_关注点是如何运作的吗?它只是您包含在类中的一个模块。迁移只是一个类。从字面上看,这与模型是一样的。 (3认同)