建议您将这些信息存储在一个表中。根据您的要求。似乎使用一个好的多态模型会更好。
代码可能是这样的。
module MultiAttr
def self.included(base)
base.send :extend, ClassMethods
end
module ClassMethods
def multi_attr(*args)
args.each do |attr_name|
class_eval <<-EOF
has_many attr_#{attr_name}, :class_name => "MultiAttributes", :as => :owner,
:conditions => {:key => '#{attr_name.singularize}'}
def add_#{attr_name.singularize}(val)
self.attr_#{attr_name}.create(:key => #{attr_name.singularize}, :value => val)
#{attr_name}
end
def #{attr_name}
self.attr_#{attr_name}.map(&:to_attr_model)
end
EOF
end
end
end
end
class AttrModel < String
def initialize(record)
@record = record
super(record.value)
end
def remove
@record.destroy
end
end
#owner_type, owner_id, key, value
class MultiAttribute < ActiveRecord::Base
belongs_to :owner, :polymorphic => true
def to_attr_model
@attr_model ||= AttrModel.new(self)
end
end
如何使用
class User < ActiveRecord::Base
include MultiAttr
multi_attr :emails, :addresses
end
user.emails #=> ["abc@example.com"]
user.add_email "qq@example.com" #=>
user.emails.first.remove
这些代码未经测试。但这是我的基本想法。