虽然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
然后你可以这样做:
rails g model Person name:string title:string avatar:attachment
这将创建以下迁移:
def self.up
create_table :people do |t|
t.string :name
t.string :title
t.attachment :avatar
t.timestamps
end
end
如果您运行迁移,
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)
希望这有所帮助!