我在相同的助手中有一些迁移
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
对于模型。
Solution
Add config.autoload_paths += Dir["#{config.root}/db/migrate/concerns/**/"]
to config/application.rb
Create 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
Use it:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)