Sha256: 3a62c79debf0f2bfc44a86d6dac7a3adf0d3a9ba62a62553f202aa4875434de6

Contents?: true

Size: 1.08 KB

Versions: 2

Compression:

Stored size: 1.08 KB

Contents

require 'rails/generators'
require 'rails/generators/active_record'

module AutomaticForeignKey
  class MigrationGenerator < ::ActiveRecord::Generators::Base
    argument :name, :default => 'create_foreign_keys'

    def self.source_root
      File.expand_path(File.join(File.dirname(__FILE__), 'templates'))
    end

    def create_migration_file
      set_local_assigns!
      migration_template 'migration.rb', "db/migrate/#{file_name}"
    end

    protected
    attr_reader :foreign_keys

    def set_local_assigns!
      @foreign_keys = determine_foreign_keys
    end

    def determine_foreign_keys
      foreign_keys = []
      connection = ::ActiveRecord::Base.connection
      connection.tables.each do |table_name|
        connection.columns(table_name).each do |column|
          references = ::ActiveRecord::Base.references(table_name, column.name)
          foreign_keys << ::RedhillonrailsCore::ActiveRecord::ConnectionAdapters::ForeignKeyDefinition.new(nil, table_name, column.name, references.first, references.last) if references
        end
      end
      foreign_keys
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
automatic_foreign_key-1.1.8 lib/generators/automatic_foreign_key/migration_generator.rb
automatic_foreign_key-1.1.7 lib/generators/automatic_foreign_key/migration_generator.rb