Reputation: 1855
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.
Upvotes: 7
Views: 8872
Reputation: 1349
you should use serialize :hash
to the model and then use it while save into the database.
Upvotes: 1
Reputation: 106
You can use :json datatype, available in latest postgres 9.3 version onwards, it would be easy to save hash.
Upvotes: 3
Reputation: 311
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
Upvotes: 8