将JSON数据存储在mysql中

我有一个组织表例如

ID, name, address, phone, email, etc... 

现在我想添加多个地址,电话和电子邮件。

这是在这样的电子邮件列中存储json数据的好方法

 [ "address2@example2.com", "address2@example2.com", "address2@example2.com" ] 

或者为电子邮件创建另一个表,为电话等创建另一个表…

如果存储json数据更好 – 在rails中使用它的最佳方法是什么?

这是我发现的

http://api.rubyonrails.org/classes/ActiveRecord/Base.html

在文本列中保存数组,散列和其他不可映射的对象

将数据作为JSON字符串存储在单个数据库字段中意味着您将无法使用SQL操作/查询数据 – 这种方式无法将数据存储在数据库中,您也可以将其存储在文本中文件。

我建议您的组织表和表之间的电子邮件地址和电话号码之间存在一对多的关系。 查看解释不同关系类型的video

建议您将这些信息存储在一个表中。 根据你的要求。似乎使用一个好的多态模型会更好。

代码可能是这样的。

 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 

这些代码没有经过测试 但这是我的基本想法。