Using Rails Serialize to Save Hash to Database

Using Rails serialize to save hash to database

The column type is wrong. You should use Text instead of String. Therefore, your migration should be:

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

Then Rails will properly convert it into YAML for you (and perform proper serialization). Strings fields are limited in size and will only hold especially-small values.

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)

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

rails How to save a serialized hash

First thing on your migration file make sure that you are saving your fields as a test like

def self.up
add_column : hotels, : address, :text
end

Then Rails will convert it into YAML / Hash for you (and perform proper serialization).

Wish you the best of luck.

PS take a look at https://stackoverflow.com/a/6702790/1380867

Rails 3 serialized hash values saving but not persisting

Remove attr_accessible :pending_changes and attr_accessor :pending_changes from the model, since you have a column in the database , so no need of using attr_accessible, attr_accessor. Use the model code as below and try.

class Subscription < ActiveRecord::Base
serialize :pending_changes, Hash
end

saving a hash to serialize Hash column in mysql but getting error

I'm pretty sure that the problem is update_column rather than anything else in your code. update_column doesn't work with serialized attributes as documented in the rails issues.

If you need to set the value after_save you might have to convert to yaml yourself:

self.update_column(:mig_serializer_frag, a.to_yaml)

Serialized hash cannot be saved on postgres database

Your format appears to be a dump of a Ruby Hash. serialize is done using YAML. It would look like this.

{ first: "1", second: "0", third: "0", fourth: "0", fifth: "1"}

But there's a better way. Since you're using Postgres you can take advantage of Postgres JSONB and send the data as JSON. The serialization will be handled for you, you have all the power of Postgres's JSON search facilities, and JSON is a standard format that most languages can produce.

{ "first": "1", "second": "0", "third": "0", "fourth": "0", "fifth": "1"}

create_table "contacts", force: :cascade do |t|
...
t.jsonb :areas_of_interest
t.index [:areas_of_interest], using: :gin
end

Nothing special is needed in Contact. Use contact.areas_of_interest like any other field, but it can take Hashes and Arrays.



Related Topics



Leave a reply



Submit