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
模型的东西。
解
添加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)
我认为你可以这样做:
# 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)
归档时间: |
|
查看次数: |
419 次 |
最近记录: |