Using Rails serialize to save hash to database

Using Rails serialize to save hash to database

Asked on January 10, 2019 in Ruby on Rails.
Add Comment


  • 2 Answer(s)

    Use Text instead of String  migration: 

    def self.up
      add_column :users, :multi_wrong, :text
    end
    

    The properly convert it into YAML and perform proper serialization. Strings fields are limited in size and will only hold especially-small value.

    Answered on January 10, 2019.
    Add Comment

    A implementation  depend on  database, but PostgreSQL now has json and jsonb columns  can natively store in hash/object data.

    change your migration:

    class Migration0001
      def change
       add_column :users, :location_data, :json, default: {}
      end
    end
    

    Migration:

    $ rails g migration add_location_data_to_users location_data:text
    

    should create:

    class Migration0001
      def change
       add_column :users, :location_data, :text
      end
    end
    

    Class:

    class User < ActiveRecord::Base
      serialize :location_data
    end
    

    Available Actions:

    b = User.new
      b.location_data = [1,2,{foot: 3, bart: "noodles"}]
    b.save
    

    utilize postgresql hstore: 

    class AddHstore < ActiveRecord::Migration 
      def up
       enable_extension :hstore
    end
     
      def down
       disable_extension :hstore
      end
    end
     
    class Migration0001
      def change
       add_column :users, :location_data, :hstore
      end
    end
    

    Answered on January 10, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.