我正在创建一个与Active Record紧密集成的Rails gem. gem需要定义许多字段.例如:
class User < ActiveRecord::Base # requires 'avatar_identifier','avatar_extension','avatar_size' has_attached :avatar end
有可能有类似的东西:
rails g model user name:string avatar:attached
导致:
create_table :users do |t| t.string :name t.string :avatar_identifier t.string :avatar_extension t.integer :avatar_size end
如果这是不可能的,任何方式:
create_table :users do |t| t.string :name t.attached :avatar end
生成多个字段?谢谢!
解决方法
虽然普拉文确实指出了正确的方向,但我发现实施它并不简单.我做了以下,我在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",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)
希望这可以帮助!!