我现在的做法是增加一个 Description Model
class Description < ActiveRecord::Base
#fields: entity_type, entity_id, name, content
belongs_to :entity, :polymorphic => true
after_save :check_content
def check_content
self.destroy if self.content.blank?
end
end
class ActiveRecord::Base
def self.has_descriptions(descriptions)
descriptions.each do |name, desc|
class_eval <<-EOV
has_one name.to_sym, :class_name => "Description", :as => :entity, :conditions => { :name => name.to_s }, :dependent => :destroy
accepts_nested_attributes_for name.to_sym, :allow_destroy => true
delegate :content, :to => name.to_sym, :prefix => true, :allow_nil => true
EOV
end
end
end
class YourModel < ActiveRecord::Base
DESCRIPTIONS = {
:field_a => "XXX",
:field_b => "XXX",
:field_c => "XXX"
}
has_descriptions DESCRIPTIONS
end
#1 楼 @Rei 不知道这样合不合适,到后期可能这个表记录会很大