how to keep a hash value in the table column in ra

2019-03-12 22:59发布

i am very new to rails . I am having a table holding all users basic information like

users(id,name,email) now i am trying to keep some additional information of these users in a separate table like

user_details(id,user_id,additional_info)

I have created this user_details table . Now i try to keep some default records for checking . how to keep the hash value of the user's additional details in the additional_info like if my additional details are user's (designation,salary,prjtname) in the column additional_info of the User_details table.

Also what datatype i have to give for this additional_info column of the User_details table. Please give some suggestions ..

2条回答
做自己的国王
2楼-- · 2019-03-12 23:33

The data type for that column must be text so in your migrations you can specify:

add_column :user_details, :additional_info, :text

Then in your model you have to specify that this column will contain a hash and you do that with the serialize command:

class UserDetail < ActiveRecord::Base
  serialize :additional_info

After that you can save hash information.

@ud = UserDetail.new
@ud.additional_info = {:salary => 1000000}
@ud.save
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-03-12 23:41

As of MySQL 5.7.8 there is a support for a native JSON data type, so saving a hash is much more direct and can be searchable and more:
https://dev.mysql.com/doc/refman/5.7/en/json.html

查看更多
登录 后发表回答