新手问题 如何处理动态 data columns 的问题?

yehualiu · 2014年07月03日 · 最后由 nickcen 回复于 2014年07月03日 · 2294 次阅读

请问:我的项目里,是由客户上传数据来存储到网站的数据库里,但客户上传的数据的 table 的 columns 是动态变化的,也就是不同的客户可能上传的数据的例不一样,这种情况下在 Rails 项目中的 active record 如何处理?谢谢!

序列化 hash,如果是 pg 有 hash/json 类型扩展。

我现在的做法是增加一个 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 不知道这样合不合适,到后期可能这个表记录会很大

楼上两位的方案已经很明确了,不过这需求要再仔细分析一下,感觉是否一定要

楼主的意思是要支持用户自定义数据列?可以 google 一下自定义模型,很多 CRM 软件都有这种支持。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号