Alexei
Alexei

Reputation: 127

Using ActiveRecord serialize with Hash not working?

I've been reading up on the use of serialize from ActiveRecord, and I thought I understood how to use it, but my attempts are failing so I'm not sure if what I want is even possible this way? What I want is to store a simple hash linking id's of objects called accruals to a number of days. For example {"1" => "12", "5" => "24"}. I set this up as follows:

class User < ActiveRecord::Base
      serialize :accrual_days, Hash
end

And for the database

def self.up
    unless column_exists? :users, :accrual_days
        add_column :users, :accrual_days, :text
    end
end

I then went into the rails console, and inputted these commands:

User.find(1).accrual_days

=> nil

User.find(1).accrual_days = {"1"=>"12"}

=> {"1"=>"12"}

User.find(1).accrual_days

=> nil

It seems like the accrual_days are being set, but then it doesn't persist. I tried saving the user after setting the accrual day, and storing it as string instead of text in the database, but the problem persists. What am I doing wrong?

Upvotes: 0

Views: 1680

Answers (1)

rwilliams
rwilliams

Reputation: 21497

You're not saving the values in the database.

Try

user = User.find(1)

user.accrual_days = {"1"=>"12"}

user.save

User.find(1).accrual_days

Upvotes: 4

Related Questions