【问题标题】:Rails share code between migrations (aka concerns)Rails 在迁移之间共享代码(又名关注点)
【发布时间】:2016-11-05 12:51:13
【问题描述】:

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

  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 的东西。

【问题讨论】:

    标签: ruby activerecord raise


    【解决方案1】:

    我认为你可以这样做:

    # 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
    

    【讨论】:

    • 不错。但对我来说太明确了。我想为模型找到类似 concerns 的东西。
    • 哦,好吧,如果不适合您,请见谅。
    • @Arsen:你知道关注点是如何工作的吗?它只是一个包含在类中的模块。迁移只是一个类。从字面上看,这与模型相同。
    • @SergioTulentsev 我现在知道了。因为我刚刚实现了。
    【解决方案2】:

    解决方案

    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
    

    【讨论】:

      猜你喜欢
      • 2012-05-09
      • 2011-04-14
      • 2012-03-05
      • 2014-07-23
      • 1970-01-01
      • 1970-01-01
      • 2014-09-24
      • 1970-01-01
      • 2016-11-05
      相关资源
      最近更新 更多