Saving JSON data in mysql

I have an organization table like

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

Now I want to add some addresses, phones and emails.

Is this a good way to store json data in an email column such as

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

Or create another table only for letters, and another for phones, etc.

If it is better to store json data - what is the best way to use it on rails?

+7
source share
3 answers

Here is what i found

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

Saving arrays, hashes, and other incompatible objects in text columns

+7
source

Storing data as JSON strings in one database field means that you cannot manipulate / query data using SQL - what kind of data storage point wins the database, you can also save it in a text file.

I would recommend a one-to-many relationship between your organization table and tables for email addresses and phone numbers. Watch a video explaining different types of relationships

+1
source

suggest storing this information in one table. according to your requirement. Using a good polymorphic model seems to be better.

Code may be like.

 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 

how to use

 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 

these codes have not been tested. but its main idea.

0
source

All Articles