Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - How to save a hash to the DB and using it as a hash once you pull it form the DB (not pulling it as a sting)

If I save a hash to the DB

hash_value = {"1"=>"val1", "2"=>"val2", "3"=>"val3", "4"=>"val4"}
@page.update(hash: hash_value)

Then try and loop through each key of the hash on the page page

hash = @page.hash 

<%= hash.each do |key, value| %>

 <%= value %>

<% end %>

I get the error undefined method 'each' for #<String:0x007fdda1d8b568>. This error made me realise it is saved saved as a string to the DB.

How do I make it save as a hash so when I pull it rom the DB it is in a hash not a string? Doing some research I found serialize but I cant make out how to use it properly. Is it used to change the DB table to have all values saved in that table be hashes? If so what is added in the migration file to do that?

    create_table :pages do |t|

      t.timestamps null: false
      t.text  :title
      t.text  :content_top
      t.text  :content_bottom
      t.text  :hash

      t.timestamps null: false
    end

Just confused as to how saving a hash to the DB and calling it as a hash is accomplished.

like image 775
Rob Avatar asked Feb 27 '16 03:02

Rob


2 Answers

The column type for :hash on :pages table is text, which is the correct column type to use when you wish for a column to store a hash. You must now also indicate on the Page model that you wish to serialize this column. Something like this:

class Page < ActiveRecord::Base
  serialize :hash

Then you can attempt to test your new setup like this:

@page = Page.new
@page.hash = {"1"=>"val1", "2"=>"val2", "3"=>"val3", "4"=>"val4"}
@page.save
like image 53
TJR Avatar answered Dec 02 '22 21:12

TJR


You can use :json datatype, available in latest postgres 9.3 version onwards, it would be easy to save hash.

like image 41
yogendra689 Avatar answered Dec 02 '22 20:12

yogendra689