我在相同的helper中进行了一些迁移。
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这样的模型。
发布于 2016-07-04 04:23:56
解决方案
向config/application.rb添加config.autoload_paths += Dir["#{config.root}/db/migrate/concerns/**/"]
在其中创建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发布于 2016-07-04 03:50:30
我认为你可以这样做:
# 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
endhttps://stackoverflow.com/questions/38173699
复制相似问题