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

前端 未结 3 1159
我在风中等你
我在风中等你 2021-02-04 09:14

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 infor

相关标签:
3条回答
  • 2021-02-04 09:30

    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

    0 讨论(0)
  • 2021-02-04 09:37

    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
    
    0 讨论(0)
  • 2021-02-04 09:49

    Another alternative would be to use JSON fields on the model. The migration would have something like:

    create_table :events do |t|
      t.json 'payload'
    end
    
    0 讨论(0)
提交回复
热议问题