我在相同的帮助者中进行了一些迁移
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
我每次都试图避免复制粘贴它们。有没有办法在迁移之间共享代码而不用猴子修补基类?我希望为模型找到类似concerns
的内容。
答案 0 :(得分:4)
<强>解决方案强>
将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
使用它:
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
答案 1 :(得分:2)
我认为你可以这样做:
# lib/helper.rb
module Helper
def always_used_on_migrations
'this helps'
end
end
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