0

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?

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I know I posted this a long time ago but better to accept an answer late than never!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.