Ruby on Rails自定义迁移生成器

Kev*_*tre 6 gem ruby-on-rails

我正在创建一个与Active Record紧密集成的Rails gem.gem需要定义许多字段.例如:

class User < ActiveRecord::Base
  # requires 'avatar_identifier', 'avatar_extension', 'avatar_size'
  has_attached :avatar
end
Run Code Online (Sandbox Code Playgroud)

有可能有类似的东西:

rails g model user name:string avatar:attached
Run Code Online (Sandbox Code Playgroud)

导致:

create_table :users do |t|
  t.string :name
  t.string :avatar_identifier
  t.string :avatar_extension
  t.integer :avatar_size
end
Run Code Online (Sandbox Code Playgroud)

如果这是不可能的,任何方式:

create_table :users do |t|
  t.string :name
  t.attached :avatar
end
Run Code Online (Sandbox Code Playgroud)

生成多个字段?谢谢!

nat*_*vda 5

虽然 Pravin 确实指出了正确的方向,但我发现实施它并不简单。我做了以下操作,我在config/initializers(名称不相关)中添加了一个文件,其中包含以下内容:

require 'active_support'
require 'active_record'

class YourApplication
  module SchemaDefinitions

    module ExtraMethod
      def attachment(*args)
        options = args.extract_options!
        args.each do |col|
          column("#{col}_identifier", :string, options)
          column("#{col}_extension", :string, options)
          column("#{col}_size", :integer, options)
        end
      end
    end

    def self.load!
      ::ActiveRecord::ConnectionAdapters::TableDefinition.class_eval { include YourApplication::SchemaDefinitions::ExtraMethod }
    end

  end
end


ActiveSupport.on_load :active_record do
  YourApplication::SchemaDefinitions.load!
end
Run Code Online (Sandbox Code Playgroud)

那么你可以做这样的事情:

rails g model Person name:string title:string avatar:attachment
Run Code Online (Sandbox Code Playgroud)

这将创建以下迁移:

def self.up
  create_table :people do |t|
    t.string :name
    t.string :title
    t.attachment :avatar

    t.timestamps
  end
end
Run Code Online (Sandbox Code Playgroud)

如果然后运行迁移,rake db:migrate它将创建以下Person模型:

ruby-1.9.2-p0 > Person
 => Person(id: integer, name: string, title: string, avatar_identifier: string, avatar_extension: string, avatar_size: integer, created_at: datetime, updated_at: datetime) 
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!!