2

I have a class including ActiveModel that needs to have some "associations", like this:

a      = ActiveModelClass.new
a.user = User.find(1)

I'm just using an attr_accessor for this:

attr_accessor :user

### Elsewhere ###

a.user.name # => "Kevin"

So far so good. But now I want to serialize it into JSON:

json = a.to_json
b    = ActiveModelClass.new(ActiveSupport::JSON.decode(json))

But now, user is a hash:

b.user.class # => Hash

How can I cleanly restore these "associations" as objects of the classes they originally were?

Kevin Griffin
  • 14,084
  • 7
  • 28
  • 23

1 Answers1

0

I'm a little confused: I have a feeling you've abstracted your example to the point where it's just hard to understand. Do you have something like this?

b.user 
=> {:name => "Kevin", :email => "kev@foo.foo"}

?

if so, you can make a user object out of this hash just by passing it to the .new or .create method:

user = User.create(b.user) 

You can then do what you want with this user object, including setting b.user equal to it.

Max Williams
  • 32,435
  • 31
  • 130
  • 197